'use client';

import { useEffect, useRef, useState } from 'react';
import { loadGoogleMapsScript, DARK_MAP_STYLES } from '@/lib/google-maps';
import { AlertCircle } from 'lucide-react';

interface DeliveryMapProps {
  lat: number;
  lng: number;
  address?: string;
}

export default function DeliveryMap({ lat, lng, address }: DeliveryMapProps) {
  const mapRef = useRef<HTMLDivElement>(null);
  const gmapInstanceRef = useRef<any>(null);
  const markerInstanceRef = useRef<any>(null);
  const infoWindowRef = useRef<any>(null);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;

    loadGoogleMapsScript()
      .then((google) => {
        if (!mounted || !mapRef.current) return;

        const centerLocation = { lat, lng };

        if (!gmapInstanceRef.current) {
          const map = new google.maps.Map(mapRef.current, {
            center: centerLocation,
            zoom: 15,
            styles: DARK_MAP_STYLES,
            disableDefaultUI: false,
            zoomControl: true,
            gestureHandling: 'greedy',
            mapTypeControl: false,
            streetViewControl: false,
            fullscreenControl: true,
          });

          gmapInstanceRef.current = map;

          const marker = new google.maps.Marker({
            position: centerLocation,
            map,
            animation: google.maps.Animation.DROP,
            title: address || 'Delivery Location',
            icon: {
              path: google.maps.SymbolPath.CIRCLE,
              scale: 8,
              fillColor: '#10b981',
              fillOpacity: 1,
              strokeColor: '#ffffff',
              strokeWeight: 2,
            },
          });
          markerInstanceRef.current = marker;

          if (address) {
            const infoWindow = new google.maps.InfoWindow({
              content: `
                <div style="padding: 4px 6px; font-family: sans-serif; color: #111827;">
                  <strong style="color: #059669; font-size: 13px;">📍 Delivery Location</strong>
                  <p style="margin: 4px 0 2px 0; font-size: 11px; max-width: 200px;">${address}</p>
                  <span style="font-size: 10px; color: #6b7280; font-family: monospace;">${lat.toFixed(5)}, ${lng.toFixed(5)}</span>
                </div>
              `,
            });
            infoWindowRef.current = infoWindow;
            infoWindow.open(map, marker);

            marker.addListener('click', () => {
              infoWindow.open(map, marker);
            });
          }
        } else {
          // Update location on change
          gmapInstanceRef.current.setCenter(centerLocation);
          if (markerInstanceRef.current) {
            markerInstanceRef.current.setPosition(centerLocation);
          }
        }

        setLoading(false);
      })
      .catch((err) => {
        if (!mounted) return;
        console.error('Failed to load Google Maps:', err);
        setError(err.message || 'Could not load Google Maps');
        setLoading(false);
      });

    return () => {
      mounted = false;
    };
  }, [lat, lng, address]);

  return (
    <div className="relative w-full h-[220px] rounded-2xl overflow-hidden border border-white/10 shadow-inner bg-[#0d1117]">
      {/* Floating Deliveryman GIF Badge Overlay */}
      <div className="absolute top-2.5 right-2.5 z-10 bg-[#090d16]/90 border border-white/10 rounded-xl px-2.5 py-1.5 backdrop-blur-md shadow-lg flex items-center gap-2 pointer-events-none">
        <div className="h-6 w-6 rounded-lg bg-emerald-500/10 border border-emerald-500/20 overflow-hidden flex items-center justify-center shrink-0">
          <img 
            src="/assets/deliveryman.gif" 
            alt="Deliveryman" 
            className="h-full w-full object-cover scale-125"
          />
        </div>
        <span className="text-[10px] font-extrabold uppercase text-emerald-400 tracking-wider">
          Live Location
        </span>
      </div>

      {loading && (
        <div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-[#0d1117]/90 text-gray-400 backdrop-blur-sm gap-2">
          <div className="h-5 w-5 rounded-full border-2 border-emerald-500 border-t-transparent animate-spin" />
          <span className="text-xs text-emerald-400 font-medium">Loading Google Maps...</span>
        </div>
      )}

      {error ? (
        <div className="absolute inset-0 z-20 flex flex-col items-center justify-center p-4 text-center bg-red-950/20 text-red-400 gap-2">
          <AlertCircle className="h-5 w-5" />
          <p className="text-xs">{error}</p>
        </div>
      ) : (
        <div ref={mapRef} className="w-full h-full" />
      )}
    </div>
  );
}
