import React, { useState, useEffect, useRef, useMemo } from 'react';
import { MapContainer, TileLayer, Marker, Polyline, Popup, useMap } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

interface NavModalProps {
  isOpen: boolean;
  onClose: () => void;
  routeData: {
    origin: { lat: number; lng: number } | null;
    destination: { lat: number; lng: number; name: string } | null;
  };
}

interface OSRMRoute {
  geometry: {
    coordinates: number[][];
    type: string;
  };
  legs: { distance: number; duration: number }[];
  distance: number;
  duration: number;
}

const FitBounds = ({ coords }: { coords: [number, number][] }) => {
  const map = useMap();
  useEffect(() => {
    if (coords.length > 0) {
      map.fitBounds(coords, { padding: [60, 60], maxZoom: 15 });
    }
  }, [map, coords]);
  return null;
};

export const LocationNavigationModal: React.FC<NavModalProps> = ({ isOpen, onClose, routeData }) => {
  const [routeGeometry, setRouteGeometry] = useState<[number, number][] | null>(null);
  const [isSearchingRoute, setIsSearchingRoute] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [routeInfo, setRouteInfo] = useState<{ distance: string; duration: string } | null>(null);

  const fetchLockRef = useRef(false);

  const originLat = routeData?.origin?.lat;
  const originLng = routeData?.origin?.lng;
  const destLat = routeData?.destination?.lat;
  const destLng = routeData?.destination?.lng;

  useEffect(() => {
    if (!isOpen || !originLat || !originLng || !destLat || !destLng) {
      setRouteGeometry(null);
      setError(null);
      setRouteInfo(null);
      return;
    }

    if (fetchLockRef.current) return;

    const calculateOptimalRoute = async () => {
      try {
        setIsSearchingRoute(true);
        fetchLockRef.current = true;

        const url = `https://router.project-osrm.org/route/v1/driving/${originLng},${originLat};${destLng},${destLat}?overview=full&geometries=geojson`;
        const res = await fetch(url);
        if (!res.ok) throw new Error(`OSRM error: ${res.status}`);
        const data: { code: string; routes: OSRMRoute[] } = await res.json();
        if (data.code !== 'Ok' || !data.routes?.length) throw new Error('Không tìm thấy lộ trình phù hợp');

        const route = data.routes[0];
        const coords = route.geometry.coordinates.map((c: number[]) => [c[1], c[0]] as [number, number]);
        setRouteGeometry(coords);

        const hours = Math.floor(route.duration / 3600);
        const minutes = Math.round((route.duration % 3600) / 60);
        const durationStr = hours > 0 ? `${hours}h${minutes}p` : `${minutes}p`;
        setRouteInfo({
          distance: (route.distance / 1000).toFixed(1),
          duration: durationStr
        });
      } catch (err: any) {
        setError(err.message);
      } finally {
        setIsSearchingRoute(false);
        fetchLockRef.current = false;
      }
    };

    calculateOptimalRoute();

    return () => {
      fetchLockRef.current = false;
      setIsSearchingRoute(false);
    };
  }, [isOpen, originLat, originLng, destLat, destLng]);

  const userIcon = useMemo(() => L.divIcon({
    className: '!bg-transparent !border-none',
    html: `<div class="w-8 h-8 bg-blue-600 rounded-full border-2 border-white shadow-xl flex items-center justify-center"><div class="w-2 h-2 bg-white rounded-full"></div></div>`,
    iconSize: [32, 32],
    iconAnchor: [16, 16]
  }), []);

  const destIcon = useMemo(() => L.divIcon({
    className: '!bg-transparent !border-none',
    html: `<div class="w-8 h-8 bg-red-600 rounded-full border-2 border-white shadow-xl flex items-center justify-center text-white text-xs font-black">Đ</div>`,
    iconSize: [32, 32],
    iconAnchor: [16, 16]
  }), []);

  if (!isOpen) return null;

  const center: [number, number] = routeData.origin && routeData.destination
    ? [(routeData.origin.lat + routeData.destination.lat) / 2, (routeData.origin.lng + routeData.destination.lng) / 2]
    : [0, 0];

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/60 backdrop-blur-sm p-0 sm:p-4">
      <div className="bg-slate-900 border border-slate-700 w-full h-full sm:w-auto sm:max-w-4xl sm:h-[85vh] rounded-t-2xl sm:rounded-2xl overflow-hidden flex flex-col shadow-2xl animate-in zoom-in-95 duration-200">
        {/* Modal Header */}
        <div className="p-4 bg-slate-800 border-b border-slate-700 flex items-center justify-between shrink-0">
          <div>
            <h3 className="text-md sm:text-lg font-bold text-white flex items-center gap-2">
              📍 Chỉ đường đến: <span className="text-blue-400">{routeData.destination?.name}</span>
            </h3>
            <p className="text-xs text-gray-400 mt-0.5">Tuyến đường ngắn nhất từ vị trí hiện tại của bạn</p>
            {routeInfo && (
              <div className="flex items-center gap-3 mt-1.5">
                <span className="text-xs font-bold text-blue-300">{routeInfo.distance} km</span>
                <span className="text-xs text-gray-500">|</span>
                <span className="text-xs font-bold text-green-300">~{routeInfo.duration}</span>
              </div>
            )}
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white text-sm font-bold px-3 py-1.5 rounded-lg bg-gray-800 hover:bg-gray-700 transition-colors"
          >
            Đóng [X]
          </button>
        </div>

        {/* Map Container */}
        <div className="relative flex-1 bg-slate-950">
          <MapContainer
            center={center}
            zoom={14}
            className="h-full w-full"
            zoomControl={true}
            attributionControl={false}
          >
            <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution="" />
            {routeData.origin && (
              <Marker position={[routeData.origin.lat, routeData.origin.lng]} icon={userIcon}>
                <Popup>
                  <div className="text-xs font-bold text-blue-600">Bạn đang ở đây</div>
                </Popup>
              </Marker>
            )}
            {routeData.destination && (
              <Marker position={[routeData.destination.lat, routeData.destination.lng]} icon={destIcon}>
                <Popup>
                  <div className="text-xs font-bold text-red-600">{routeData.destination.name}</div>
                </Popup>
              </Marker>
            )}
            {routeGeometry && <FitBounds coords={routeGeometry} />}
            {routeGeometry && (
              <Polyline positions={routeGeometry} color="#2563eb" weight={6} opacity={0.9} smoothFactor={1} />
            )}
          </MapContainer>

          

          {error && (
            <div className="absolute top-4 left-1/2 -translate-x-1/2 bg-red-900 text-white text-xs px-3 py-1.5 rounded-lg shadow-lg z-[1000]">
              {error}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
