/*
 * Distribution Map Component for Enterprise Dashboard
 * Shows delivery routes and shipment status across the network with real Leaflet map
 */

import React, { useState } from 'react';
import { MapContainer, TileLayer, Marker, Polyline, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';
import { Badge } from '../ui/Badge';
import { Button } from '../ui/Button';
import {
  MapPin,
  Truck,
  CheckCircle,
  Clock,
  AlertTriangle,
  Package,
  Eye,
  Info,
  Route,
  Navigation,
  Map as MapIcon
} from 'lucide-react';
import { useTranslation } from 'react-i18next';

// Fix for default marker icons in Leaflet
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});

interface RoutePoint {
  tenant_id: string;
  name: string;
  address: string;
  latitude: number;
  longitude: number;
  status: 'pending' | 'in_transit' | 'delivered' | 'failed';
  estimated_arrival?: string;
  actual_arrival?: string;
  sequence: number;
  id?: string;
}

interface RouteData {
  id: string;
  route_number: string;
  total_distance_km: number;
  estimated_duration_minutes: number;
  status: 'planned' | 'in_progress' | 'completed' | 'cancelled';
  route_sequence?: RoutePoint[];  // Backend returns route_sequence, not route_points
}

interface ShipmentStatusData {
  pending: number;
  in_transit: number;
  delivered: number;
  failed: number;
}

interface DistributionMapProps {
  routes?: RouteData[];
  shipments?: ShipmentStatusData;
}

// Helper function to create custom markers
const createRouteMarker = (color: string, number: number) => {
  return L.divIcon({
    className: 'custom-route-marker',
    html: `<div style="background-color: ${color}; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 3px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.3); font-size: 14px; font-weight: bold; color: white;">${number}</div>`,
    iconSize: [32, 32],
    iconAnchor: [16, 16]
  });
};

const DistributionMap: React.FC<DistributionMapProps> = ({
  routes = [],
  shipments = { pending: 0, in_transit: 0, delivered: 0, failed: 0 }
}) => {
  const { t } = useTranslation('dashboard');

  const renderMapVisualization = () => {
    if (!routes || routes.length === 0) {
      return (
        <div className="h-full min-h-[400px] flex items-center justify-center rounded-xl border-2 border-dashed" style={{ borderColor: 'var(--border-secondary)', backgroundColor: 'var(--bg-secondary)' }}>
          <div className="text-center px-6">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center mb-4 mx-auto shadow-sm"
              style={{
                backgroundColor: 'var(--color-info-50)',
              }}
            >
              <MapPin className="w-10 h-10" style={{ color: 'var(--color-info-500)' }} />
            </div>
            <h3 className="text-lg font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>
              {t('enterprise.no_active_routes', 'Sin rutas activas')}
            </h3>
            <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
              {t('enterprise.no_shipments_today', 'No hay envíos programados para hoy')}
            </p>
          </div>
        </div>
      );
    }

    // Find active routes with GPS data
    const activeRoutes = routes.filter(route =>
      (route.status === 'in_progress' || route.status === 'planned') &&
      route.route_sequence &&
      route.route_sequence.length > 0 &&
      route.route_sequence.every(point => point.latitude && point.longitude)
    );

    if (activeRoutes.length === 0) {
      return (
        <div className="h-full min-h-[400px] flex items-center justify-center rounded-xl border-2 border-dashed" style={{ borderColor: 'var(--border-secondary)', backgroundColor: 'var(--bg-secondary)' }}>
          <div className="text-center px-6">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center mb-4 mx-auto shadow-sm"
              style={{
                backgroundColor: 'var(--color-success-50)',
              }}
            >
              <CheckCircle className="w-10 h-10" style={{ color: 'var(--color-success-500)' }} />
            </div>
            <h3 className="text-lg font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>
              {t('enterprise.all_routes_completed', 'Todas las rutas completadas')}
            </h3>
            <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
              {t('enterprise.no_active_deliveries', 'No hay entregas pendientes en este momento')}
            </p>
          </div>
        </div>
      );
    }

    // Calculate center point (average of all route points)
    const allPoints = activeRoutes.flatMap(route => route.route_sequence || []);
    const centerLat = allPoints.reduce((sum, p) => sum + p.latitude, 0) / allPoints.length;
    const centerLng = allPoints.reduce((sum, p) => sum + p.longitude, 0) / allPoints.length;

    // Real Leaflet map with routes
    return (
      <div className="relative h-[500px] w-full rounded-xl overflow-hidden border border-[var(--border-primary)] shadow-sm">
        <MapContainer
          center={[centerLat, centerLng]}
          zoom={6}
          style={{ height: '100%', width: '100%', zIndex: 0 }}
          scrollWheelZoom={true}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />

          {/* Render each route */}
          {activeRoutes.map((route) => {
            const points = route.route_sequence || [];
            const routeColor = route.status === 'in_progress' ? '#3b82f6' : '#f59e0b';

            // Create polyline coordinates
            const polylinePositions: [number, number][] = points.map(p => [p.latitude, p.longitude]);

            return (
              <React.Fragment key={route.id}>
                {/* Route polyline */}
                <Polyline
                  positions={polylinePositions}
                  pathOptions={{
                    color: routeColor,
                    weight: 4,
                    opacity: 0.7
                  }}
                />

                {/* Route stop markers */}
                {points.map((point, idx) => {
                  const markerColor = point.status === 'delivered' ? '#22c55e' :
                                     point.status === 'in_transit' ? '#3b82f6' :
                                     point.status === 'failed' ? '#ef4444' : '#f59e0b';

                  return (
                    <Marker
                      key={`${route.id}-${idx}`}
                      position={[point.latitude, point.longitude]}
                      icon={createRouteMarker(markerColor, point.sequence)}
                    >
                      <Popup>
                        <div className="min-w-[180px] p-1">
                          <div className="font-semibold text-sm mb-1 text-[var(--text-primary)]">{point.name}</div>
                          <div className="text-xs text-[var(--text-secondary)] mb-2">{point.address}</div>
                          <div className="flex flex-col gap-1 border-t border-[var(--border-primary)] pt-2 mt-2">
                            <div className="flex justify-between text-[10px] text-[var(--text-tertiary)]">
                              <span>Ruta:</span>
                              <span className="font-medium text-[var(--text-secondary)]">{route.route_number}</span>
                            </div>
                            <div className="flex justify-between text-[10px] text-[var(--text-tertiary)]">
                              <span>Parada:</span>
                              <span className="font-medium text-[var(--text-secondary)]">{point.sequence} / {points.length}</span>
                            </div>
                            <div className="flex justify-between text-[10px] text-[var(--text-tertiary)]">
                              <span>Estado:</span>
                              <Badge 
                                variant="outline" 
                                className="px-1.5 py-0 text-[9px] capitalize"
                                style={{
                                    backgroundColor: markerColor + '10',
                                    color: markerColor,
                                    borderColor: markerColor + '30'
                                }}
                              >
                                {point.status}
                              </Badge>
                            </div>
                          </div>
                        </div>
                      </Popup>
                    </Marker>
                  );
                })}
              </React.Fragment>
            );
          })}
        </MapContainer>

        {/* Status Legend Overlay - Refined alignment */}
        <div
          className="absolute bottom-6 right-6 p-4 rounded-xl shadow-xl z-[400] overflow-hidden"
          style={{
            backgroundColor: 'rgba(var(--bg-primary-rgb), 0.9)',
            backdropFilter: 'blur(8px)',
            border: '1px solid var(--border-primary)',
          }}
        >
          <div className="text-[10px] uppercase tracking-wider font-bold mb-3 text-[var(--text-tertiary)]">
            {activeRoutes.length} {t('enterprise.active_routes', 'Rutas Activas')}
          </div>
          <div className="space-y-2.5">
            <div className="flex items-center justify-between gap-4">
              <div className="flex items-center gap-2">
                <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: '#22c55e' }}></div>
                <span className="text-xs text-[var(--text-secondary)]">
                  {t('enterprise.delivered', 'Entregadas')}
                </span>
              </div>
              <span className="text-xs font-bold text-[var(--text-primary)]">{shipments.delivered}</span>
            </div>
            <div className="flex items-center justify-between gap-4">
              <div className="flex items-center gap-2">
                <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: '#3b82f6' }}></div>
                <span className="text-xs text-[var(--text-secondary)]">
                  {t('enterprise.in_transit', 'En Tránsito')}
                </span>
              </div>
              <span className="text-xs font-bold text-[var(--text-primary)]">{shipments.in_transit}</span>
            </div>
            <div className="flex items-center justify-between gap-4">
              <div className="flex items-center gap-2">
                <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: '#f59e0b' }}></div>
                <span className="text-xs text-[var(--text-secondary)]">
                  {t('enterprise.pending', 'Pendientes')}
                </span>
              </div>
              <span className="text-xs font-bold text-[var(--text-primary)]">{shipments.pending}</span>
            </div>
            {shipments.failed > 0 && (
              <div className="flex items-center justify-between gap-4">
                <div className="flex items-center gap-2">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: '#ef4444' }}></div>
                  <span className="text-xs text-[var(--text-secondary)]">
                    {t('enterprise.failed', 'Fallidas')}
                  </span>
                </div>
                <span className="text-xs font-bold text-[var(--text-primary)]">{shipments.failed}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="w-full">
      {renderMapVisualization()}
    </div>
  );
};

export default DistributionMap;