'use client';

import { useEffect, useRef, useState } from 'react';
import { X, MapPin, User, Phone, Clock, FileText, Send, Loader2 } from 'lucide-react';
import { apiRequest } from '@/lib/api';

interface TrackingData {
  driverName?: string;
  driverPhone?: string;
  status?: string;
  currentLat?: number;
  currentLng?: number;
  etaMinutes?: number;
  notes?: string;
  notifiedAt?: string;
}

interface TrackingModalProps {
  orderId: string;
  orderNumber: string;
  customerPhone: string;
  existingTracking?: TrackingData | null;
  onClose: () => void;
  onSaved: (tracking: TrackingData) => void;
}

const STATUS_OPTIONS = [
  { value: 'PREPARING', label: '📦 Preparing', color: 'amber' },
  { value: 'DISPATCHED', label: '🚚 Dispatched', color: 'blue' },
  { value: 'IN_TRANSIT', label: '🛣️ In Transit', color: 'indigo' },
  { value: 'DELIVERED', label: '✅ Delivered', color: 'emerald' },
];

export default function TrackingModal({
  orderId,
  orderNumber,
  customerPhone,
  existingTracking,
  onClose,
  onSaved,
}: TrackingModalProps) {
  const mapRef = useRef<HTMLDivElement>(null);
  const leafletMapRef = useRef<any>(null);
  const markerRef = useRef<any>(null);

  const [form, setForm] = useState<TrackingData>({
    driverName: existingTracking?.driverName || '',
    driverPhone: existingTracking?.driverPhone || '',
    status: existingTracking?.status || 'PREPARING',
    currentLat: existingTracking?.currentLat,
    currentLng: existingTracking?.currentLng,
    etaMinutes: existingTracking?.etaMinutes,
    notes: existingTracking?.notes || '',
  });

  const [notifyCustomer, setNotifyCustomer] = useState(false);
  const [saving, setSaving] = useState(false);
  const [mapInfo, setMapInfo] = useState('Click on the map to pin the driver location');

  // Initialize the click-to-pin map
  useEffect(() => {
    if (!mapRef.current) return;
    let mounted = true;

    const el = mapRef.current as any;
    if (el._leaflet_id) return;

    import('leaflet').then((L) => {
      if (!mounted || !mapRef.current) return;
      const container = mapRef.current as any;
      if (container._leaflet_id) return;

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

      // Center on existing pin, or Harare as default
      const initLat = form.currentLat ?? -17.8252;
      const initLng = form.currentLng ?? 31.0335;

      const map = L.map(mapRef.current!, {
        center: [initLat, initLng],
        zoom: form.currentLat ? 14 : 12,
        scrollWheelZoom: true,
      });

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19,
      }).addTo(map);

      // If there's an existing pin, show it
      if (form.currentLat && form.currentLng) {
        markerRef.current = L.marker([form.currentLat, form.currentLng], { draggable: true }).addTo(map);
        markerRef.current.on('dragend', (e: any) => {
          const pos = e.target.getLatLng();
          setForm((prev) => ({ ...prev, currentLat: pos.lat, currentLng: pos.lng }));
          setMapInfo(`📍 ${pos.lat.toFixed(5)}, ${pos.lng.toFixed(5)}`);
        });
        setMapInfo(`📍 ${form.currentLat.toFixed(5)}, ${form.currentLng.toFixed(5)}`);
      }

      // Click to drop/move pin
      map.on('click', (e: any) => {
        const { lat, lng } = e.latlng;
        setForm((prev) => ({ ...prev, currentLat: lat, currentLng: lng }));
        setMapInfo(`📍 ${lat.toFixed(5)}, ${lng.toFixed(5)}`);

        if (markerRef.current) {
          markerRef.current.setLatLng([lat, lng]);
        } else {
          markerRef.current = L.marker([lat, lng], { draggable: true }).addTo(map);
          markerRef.current.on('dragend', (de: any) => {
            const pos = de.target.getLatLng();
            setForm((prev) => ({ ...prev, currentLat: pos.lat, currentLng: pos.lng }));
            setMapInfo(`📍 ${pos.lat.toFixed(5)}, ${pos.lng.toFixed(5)}`);
          });
        }
      });

      leafletMapRef.current = map;
    });

    return () => {
      mounted = false;
      if (leafletMapRef.current) {
        leafletMapRef.current.remove();
        leafletMapRef.current = null;
        markerRef.current = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleUseCurrentLocation = () => {
    if (!navigator.geolocation) {
      alert('Geolocation is not supported by your browser.');
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const { latitude, longitude } = pos.coords;
        setForm((prev) => ({ ...prev, currentLat: latitude, currentLng: longitude }));
        setMapInfo(`📍 Live GPS: ${latitude.toFixed(5)}, ${longitude.toFixed(5)}`);
        if (leafletMapRef.current) {
          leafletMapRef.current.setView([latitude, longitude], 15);
          if (markerRef.current) {
            markerRef.current.setLatLng([latitude, longitude]);
          }
        }
      },
      (err) => alert(`GPS error: ${err.message}`),
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
    );
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const result = await apiRequest(`api/orders/${orderId}/tracking`, 'POST', {
        ...form,
        notifyCustomer,
      });
      onSaved(result);
      onClose();
    } catch (err: any) {
      alert(`Failed to save tracking: ${err.message}`);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css" crossOrigin="anonymous" />

      {/* Backdrop */}
      <div
        className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none">
        <div className="pointer-events-auto w-full max-w-2xl bg-[#0d1117] border border-white/10 rounded-2xl shadow-2xl flex flex-col max-h-[90vh] overflow-hidden">
          {/* Header */}
          <div className="flex items-center justify-between px-6 py-4 border-b border-white/10">
            <div>
              <h2 className="text-white font-bold text-lg">Update Tracking</h2>
              <p className="text-gray-400 text-xs mt-0.5">Order #{orderNumber} · {customerPhone}</p>
            </div>
            <button
              onClick={onClose}
              className="h-8 w-8 rounded-lg hover:bg-white/5 flex items-center justify-center text-gray-400 hover:text-white transition-colors cursor-pointer"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          <div className="flex-1 overflow-y-auto p-6 space-y-6">
            {/* Status */}
            <div className="space-y-2">
              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-400">Delivery Status</label>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                {STATUS_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setForm((p) => ({ ...p, status: opt.value }))}
                    className={`px-3 py-2 rounded-xl text-xs font-semibold border transition-all cursor-pointer ${
                      form.status === opt.value
                        ? 'bg-emerald-500/20 border-emerald-500/50 text-emerald-300'
                        : 'bg-white/3 border-white/10 text-gray-400 hover:border-white/20 hover:text-white'
                    }`}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Driver Info */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <label className="block text-xs font-semibold uppercase tracking-wider text-gray-400">Driver Name</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-500" />
                  <input
                    type="text"
                    value={form.driverName || ''}
                    onChange={(e) => setForm((p) => ({ ...p, driverName: e.target.value }))}
                    placeholder="John Doe"
                    className="w-full pl-9 pr-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-gray-600 outline-none focus:border-emerald-500/50"
                  />
                </div>
              </div>
              <div className="space-y-1.5">
                <label className="block text-xs font-semibold uppercase tracking-wider text-gray-400">Driver Phone</label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-500" />
                  <input
                    type="text"
                    value={form.driverPhone || ''}
                    onChange={(e) => setForm((p) => ({ ...p, driverPhone: e.target.value }))}
                    placeholder="+263..."
                    className="w-full pl-9 pr-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-gray-600 outline-none focus:border-emerald-500/50"
                  />
                </div>
              </div>
            </div>

            {/* ETA */}
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-400">ETA (minutes)</label>
              <div className="relative w-40">
                <Clock className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-500" />
                <input
                  type="number"
                  min={1}
                  value={form.etaMinutes || ''}
                  onChange={(e) => setForm((p) => ({ ...p, etaMinutes: parseInt(e.target.value) || undefined }))}
                  placeholder="e.g. 30"
                  className="w-full pl-9 pr-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-gray-600 outline-none focus:border-emerald-500/50"
                />
              </div>
            </div>

            {/* Map */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <label className="block text-xs font-semibold uppercase tracking-wider text-gray-400">Driver Location (click map to pin)</label>
                  <button
                    type="button"
                    onClick={handleUseCurrentLocation}
                    className="px-2 py-0.5 rounded-md bg-emerald-500/20 border border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/30 text-[10px] font-medium transition-colors cursor-pointer flex items-center gap-1"
                  >
                    📍 Use My GPS
                  </button>
                </div>
                <span className="text-[10px] text-emerald-400 font-mono">{mapInfo}</span>
              </div>
              <div ref={mapRef} style={{ height: '220px', width: '100%', borderRadius: '12px', overflow: 'hidden', zIndex: 1 }} className="border border-white/10" />
              <p className="text-[10px] text-gray-500">Click anywhere on the map to set position, or click "Use My GPS" for exact device location.</p>
            </div>

            {/* Notes */}
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-400">Notes (optional)</label>
              <div className="relative">
                <FileText className="absolute left-3 top-3 h-3.5 w-3.5 text-gray-500" />
                <textarea
                  value={form.notes || ''}
                  onChange={(e) => setForm((p) => ({ ...p, notes: e.target.value }))}
                  placeholder="e.g. called customer, waiting at gate..."
                  rows={2}
                  className="w-full pl-9 pr-3 py-2.5 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-gray-600 outline-none focus:border-emerald-500/50 resize-none"
                />
              </div>
            </div>

            {/* Notify Customer */}
            <label className="flex items-center gap-3 cursor-pointer p-3 rounded-xl bg-emerald-500/5 border border-emerald-500/20 hover:bg-emerald-500/10 transition-colors">
              <input
                type="checkbox"
                checked={notifyCustomer}
                onChange={(e) => setNotifyCustomer(e.target.checked)}
                className="h-4 w-4 accent-emerald-500 cursor-pointer"
              />
              <div>
                <p className="text-sm font-semibold text-emerald-300 flex items-center gap-1.5">
                  <Send className="h-3.5 w-3.5" />
                  Notify Customer via WhatsApp
                </p>
                <p className="text-[10px] text-gray-400 mt-0.5">
                  Sends a WhatsApp message to {customerPhone} with the tracking link
                </p>
              </div>
            </label>
          </div>

          {/* Footer */}
          <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-white/10">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg text-sm text-gray-400 hover:text-white hover:bg-white/5 transition-colors cursor-pointer"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-2 px-5 py-2 bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white font-semibold rounded-lg text-sm transition-all cursor-pointer shadow-md shadow-emerald-500/20"
            >
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <MapPin className="h-4 w-4" />}
              {saving ? 'Saving...' : 'Save Tracking'}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
