import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
    Truck,
    Plus,
    Package,
    MapPin,
    Calendar,
    Search,
    Filter,
    MoreVertical,
    CheckCircle,
    AlertTriangle,
    X,
    Clock,
    Eye,
} from 'lucide-react';
import {
    Button,
    StatsGrid,
    Card,
    CardContent,
    CardHeader,
    CardTitle,
    Badge,
    Input,
    Tabs,
    EmptyState,
    StatusCard,
    SearchAndFilter,
    type FilterConfig,
    getStatusColor,
} from '../../../../components/ui';
import { TabsList, TabsTrigger, TabsContent } from '../../../../components/ui/Tabs';
import { PageHeader } from '../../../../components/layout';
import { useTenant } from '../../../../stores/tenant.store';
import { useDistributionOverview } from '../../../../api/hooks/useEnterpriseDashboard';
import DistributionMap from '../../../../components/maps/DistributionMap';

const DistributionPage: React.FC = () => {
    const { t } = useTranslation(['operations', 'common', 'dashboard']);
    const { currentTenant: tenant } = useTenant();
    const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
    const [activeTab, setActiveTab] = useState<'overview' | 'routes' | 'shipments'>('overview');

    // Fetch real distribution data
    const { data: distributionData, isLoading } = useDistributionOverview(
        tenant?.id || '',
        selectedDate,
        { enabled: !!tenant?.id }
    );

    // Derive stats from real data
    const stats = [
        {
            title: t('operations:stats.active_routes', 'Rutas Activas'),
            value: distributionData?.route_sequences?.filter((r: any) => r.status === 'in_progress').length || 0,
            variant: 'info' as const,
            icon: Truck,
        },
        {
            title: t('operations:stats.pending_deliveries', 'Entregas Pendientes'),
            value: distributionData?.status_counts?.pending || 0,
            variant: 'warning' as const,
            icon: Package,
        },
        {
            title: t('operations:stats.completed_deliveries', 'Entregas Completadas'),
            value: distributionData?.status_counts?.delivered || 0,
            variant: 'success' as const,
            icon: CheckCircle,
        },
        {
            title: t('operations:stats.total_routes', 'Total Rutas'),
            value: distributionData?.route_sequences?.length || 0,
            variant: 'default' as const,
            icon: MapPin,
        },
    ];

    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('');

    const handleNewRoute = () => {
        // Navigate to create route page or open modal
        console.log('New route clicked');
    };

    // Route status configuration
    const getRouteStatusConfig = (status: string) => {
        const configs: Record<string, any> = {
            pending: {
                color: getStatusColor('warning'),
                text: t('operations:status.pending', 'Pendiente'),
                icon: Clock,
                isCritical: true
            },
            in_progress: {
                color: getStatusColor('info'),
                text: t('operations:status.in_progress', 'En Progreso'),
                icon: Truck,
                isCritical: false
            },
            completed: {
                color: getStatusColor('success'),
                text: t('operations:status.completed', 'Completada'),
                icon: CheckCircle,
                isCritical: false
            },
            failed: {
                color: getStatusColor('error'),
                text: t('operations:status.failed', 'Fallida'),
                icon: AlertTriangle,
                isCritical: true
            }
        };

        return configs[status] || {
            color: getStatusColor('neutral'),
            text: status,
            icon: Package,
            isCritical: false
        };
    };

    // Filter routes
    const filteredRoutes = distributionData?.route_sequences?.filter((route: any) => {
        const matchesSearch = route.route_number?.toLowerCase().includes(searchTerm.toLowerCase());
        const matchesStatus = !statusFilter || route.status === statusFilter;
        return matchesSearch && matchesStatus;
    }) || [];

    const filterConfig: FilterConfig[] = [
        {
            key: 'status',
            type: 'dropdown',
            label: t('operations:filters.status', 'Estado'),
            value: statusFilter,
            onChange: (value) => setStatusFilter(value as string),
            placeholder: t('operations:filters.all_statuses', 'Todos los estados'),
            options: [
                { value: 'pending', label: t('operations:status.pending', 'Pendiente') },
                { value: 'in_progress', label: t('operations:status.in_progress', 'En Progreso') },
                { value: 'completed', label: t('operations:status.completed', 'Completada') },
                { value: 'failed', label: t('operations:status.failed', 'Fallida') }
            ]
        }
    ];

    if (!tenant) return null;

    // Prepare shipment status data safely
    const shipmentStatus = {
        pending: distributionData?.status_counts?.pending || 0,
        in_transit: distributionData?.status_counts?.in_transit || 0,
        delivered: distributionData?.status_counts?.delivered || 0,
        failed: distributionData?.status_counts?.failed || 0,
    };

    return (
        <div className="space-y-6">
            <PageHeader
                title={t('operations:distribution.title', 'Distribución y Logística')}
                description={t('operations:distribution.description', 'Gestión integral de la flota de reparto y seguimiento de entregas en tiempo real')}
                actions={[
                    {
                        id: "date-select",
                        label: selectedDate,
                        variant: "outline" as const,
                        icon: Calendar,
                        onClick: () => { }, // In a real app this would trigger a date picker
                        size: "md"
                    },
                    {
                        id: "add-new-route",
                        label: t('operations:actions.new_route', 'Nueva Ruta'),
                        variant: "primary" as const,
                        icon: Plus,
                        onClick: handleNewRoute,
                        tooltip: t('operations:tooltips.new_route', 'Crear una nueva ruta de distribución'),
                        size: "md"
                    }
                ]}
            />

            {/* Stats Grid - Follows Procurement style */}
            <StatsGrid
                stats={stats}
                columns={4}
            />

            {/* Tabs Navigation - Simplified and cleaned up */}
            <Tabs
                value={activeTab}
                onValueChange={(value: string) => setActiveTab(value as 'overview' | 'routes' | 'shipments')}
                className="w-full"
            >
                <TabsList className="mb-6">
                    <TabsTrigger value="overview">
                        {t('operations:distribution.tabs.overview', 'Vista General')}
                    </TabsTrigger>
                    <TabsTrigger value="routes">
                        {t('operations:distribution.tabs.routes', 'Listado de Rutas')}
                    </TabsTrigger>
                    <TabsTrigger value="shipments">
                        {t('operations:distribution.tabs.shipments', 'Listado de Envíos')}
                    </TabsTrigger>
                </TabsList>

                {/* Content based on Active Tab */}
                <TabsContent value="overview" className="space-y-6 outline-none">
                    {/* Map Section - Integrated with Card Header style */}
                    <Card className="overflow-hidden border-[var(--border-primary)]">
                        <CardHeader className="border-b border-[var(--border-primary)] bg-[var(--bg-secondary)] py-4">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="p-2 rounded-lg bg-[var(--color-info-50)] dark:bg-[var(--color-info-900)]">
                                        <MapPin className="w-5 h-5 text-[var(--color-info)] dark:text-[var(--color-info-300)]" />
                                    </div>
                                    <div>
                                        <CardTitle className="text-lg font-bold">
                                            {t('operations:map.title', 'Mapa de Distribución')}
                                        </CardTitle>
                                        <p className="text-sm text-[var(--text-secondary)]">
                                            {t('operations:map.description', 'Visualización en tiempo real de la flota')}
                                        </p>
                                    </div>
                                </div>
                                <Badge variant="outline" className="flex items-center gap-1.5 border-[var(--border-primary)] shadow-sm py-1">
                                    <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
                                    <span className="text-xs font-semibold">{t('operations:map.live', 'En Vivo')}</span>
                                </Badge>
                            </div>
                        </CardHeader>
                        <CardContent className="p-0">
                            <div className="p-1 sm:p-2 bg-[var(--bg-primary)]">
                                <DistributionMap
                                    routes={distributionData?.route_sequences || []}
                                    shipments={shipmentStatus}
                                />
                            </div>
                        </CardContent>
                    </Card>

                    {/* Secondary sections at the bottom if needed, but keeping it clean for now */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        {/* Summary of important routes or alerts could go here */}
                    </div>
                </TabsContent>

                <TabsContent value="routes" className="space-y-6 mt-0 outline-none">
                    <SearchAndFilter
                        searchValue={searchTerm}
                        onSearchChange={setSearchTerm}
                        searchPlaceholder={t('operations:distribution.search_routes', 'Buscar rutas...')}
                        filters={filterConfig}
                    />

                    {filteredRoutes.length > 0 ? (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {filteredRoutes.map((route: any) => {
                                const statusConfig = getRouteStatusConfig(route.status);
                                return (
                                    <StatusCard
                                        key={route.id}
                                        id={route.id}
                                        statusIndicator={statusConfig}
                                        title={`${t('operations:distribution.route_number', 'Ruta')} ${route.route_number}`}
                                        subtitle={`${t('operations:distribution.vehicle', 'Vehículo')}: ${route.vehicle_id || t('common:not_available', 'N/A')}`}
                                        primaryValue={`${route.route_sequence?.length || 0}`}
                                        primaryValueLabel={t('operations:distribution.stops', 'Paradas')}
                                        metadata={[
                                            `${t('operations:distribution.distance', 'Distancia')}: ${route.total_distance_km?.toFixed(1) || 0} km`,
                                            `${t('operations:distribution.duration', 'Duración')}: ${route.estimated_duration_minutes || 0} min`,
                                            `${t('operations:distribution.savings', 'Ahorro')}: ${route.vrp_optimization_savings?.distance_saved_km?.toFixed(1) || 0} km`
                                        ]}
                                        actions={[
                                            {
                                                label: t('common:actions.view', 'Ver'),
                                                icon: Eye,
                                                onClick: () => console.log('View route', route.id),
                                                variant: 'primary'
                                            }
                                        ]}
                                    />
                                );
                            })}
                        </div>
                    ) : (
                        <Card className="border-[var(--border-primary)]">
                            <CardContent className="py-12">
                                <EmptyState
                                    icon={Truck}
                                    title={t('operations:distribution.no_routes_found', 'No se encontraron rutas')}
                                    description={t('operations:distribution.no_routes_desc', 'No hay rutas de distribución que coincidan con los filtros.')}
                                />
                            </CardContent>
                        </Card>
                    )}
                </TabsContent>

                <TabsContent value="shipments" className="space-y-6 mt-0 outline-none">
                    <SearchAndFilter
                        searchValue={''}
                        onSearchChange={() => { }}
                        searchPlaceholder={t('operations:distribution.search_shipments', 'Buscar envíos...')}
                        filters={[]}
                    />

                    <Card className="border-[var(--border-primary)]">
                        <CardContent className="py-12">
                            <EmptyState
                                icon={Package}
                                title={t('operations:distribution.shipments_list', 'Gestión de Envíos')}
                                description={t('operations:distribution.shipments_desc', 'Funcionalidad de listado detallado de envíos próximamente.')}
                            />
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    );
};

export default DistributionPage;
