'use client';

import { useEffect, useRef, useState } from 'react';
import { CheckCircle, Clock, Package, Truck, MapPin } from 'lucide-react';

interface TrackingInfo {
  tracking: {
    status: string;
    driverName?: string;
    driverPhone?: string;
    currentLat?: number;
    currentLng?: number;
    etaMinutes?: number;
    notes?: string;
    notifiedAt?: string;
    updatedAt: string;
  } | null;
  order: {
    id: string;
    orderNumber: string;
    customerName: string;
    status: string;
    deliveryAddress?: string;
    deliveryLat?: number;
    deliveryLng?: number;
    business: { name: string };
  };
}

const STATUSES = [
  { key: 'PREPARING', label: 'Preparing', icon: Package, description: 'Your order is being prepared for dispatch.' },
  { key: 'DISPATCHED', label: 'Dispatched', icon: Truck, description: 'Your order has left the store.' },
  { key: 'IN_TRANSIT', label: 'In Transit', icon: MapPin, description: 'Your order is on the way to you.' },
  { key: 'DELIVERED', label: 'Delivered', icon: CheckCircle, description: 'Your order has been delivered!' },
];

function getApiBase() {
  if (typeof window !== 'undefined') {
    return `http://${window.location.hostname}:3001`;
  }
  return 'http://localhost:3001';
}

export default function TrackingPage({ params }: { params: { orderId: string } }) {
  const [info, setInfo] = useState<TrackingInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const mapRef = useRef<HTMLDivElement>(null);
  const leafletMapRef = useRef<any>(null);

  useEffect(() => {
    const fetchTracking = async () => {
      try {
        const base = getApiBase();
        const res = await fetch(`${base}/track/${params.orderId}`);
        if (!res.ok) throw new Error('Not found');
        const data = await res.json();
        setInfo(data);
      } catch {
        setError('Tracking information not found for this order.');
      } finally {
        setLoading(false);
      }
    };
    fetchTracking();

    // Refresh every 30 seconds for live updates
    const interval = setInterval(fetchTracking, 30000);
    return () => clearInterval(interval);
  }, [params.orderId]);

  // Initialize map when we have coordinates
  useEffect(() => {
    if (!info || !mapRef.current) return;

    const driverLat = info.tracking?.currentLat;
    const driverLng = info.tracking?.currentLng;
    const destLat = info.order.deliveryLat;
    const destLng = info.order.deliveryLng;

    if (!driverLat && !destLat) return;

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

    let mounted = true;

    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',
      });

      const centerLat = driverLat ?? destLat ?? -17.8252;
      const centerLng = driverLng ?? destLng ?? 31.0335;

      const map = L.map(mapRef.current!, {
        center: [centerLat, centerLng],
        zoom: 14,
        scrollWheelZoom: false,
        zoomControl: true,
      });

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

      // Driver current location pin (green)
      if (driverLat && driverLng) {
        const driverIcon = L.divIcon({
          className: '',
          html: `<div style="background:#10b981;width:32px;height:32px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);border:3px solid white;box-shadow:0 2px 8px rgba(0,0,0,0.4);display:flex;align-items:center;justify-content:center;">
            <div style="transform:rotate(45deg);font-size:14px;">🚚</div>
          </div>`,
          iconSize: [32, 32],
          iconAnchor: [16, 32],
        });
        L.marker([driverLat, driverLng], { icon: driverIcon })
          .addTo(map)
          .bindPopup('<strong>Driver Location</strong><br/>Updated live');
      }

      // Customer delivery destination pin (red)
      if (destLat && destLng) {
        const destIcon = L.divIcon({
          className: '',
          html: `<div style="background:#ef4444;width:28px;height:28px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);border:3px solid white;box-shadow:0 2px 8px rgba(0,0,0,0.4);">
          </div>`,
          iconSize: [28, 28],
          iconAnchor: [14, 28],
        });
        L.marker([destLat, destLng], { icon: destIcon })
          .addTo(map)
          .bindPopup('<strong>📍 Delivery Destination</strong>');
      }

      // Draw line between driver and destination
      if (driverLat && driverLng && destLat && destLng) {
        L.polyline([[driverLat, driverLng], [destLat, destLng]], {
          color: '#10b981',
          dashArray: '6 8',
          weight: 2,
          opacity: 0.7,
        }).addTo(map);
      }

      leafletMapRef.current = map;
    });

    return () => {
      mounted = false;
    };
  }, [info]);

  if (loading) {
    return (
      <div className="min-h-screen bg-[#0d1117] flex items-center justify-center">
        <div className="h-10 w-10 rounded-full border-4 border-emerald-500 border-t-transparent animate-spin" />
      </div>
    );
  }

  if (error || !info) {
    return (
      <div className="min-h-screen bg-[#0d1117] flex items-center justify-center p-8 text-center">
        <div>
          <MapPin className="h-12 w-12 text-gray-600 mx-auto mb-4" />
          <h1 className="text-white text-xl font-bold mb-2">Tracking Not Found</h1>
          <p className="text-gray-400 text-sm">{error}</p>
        </div>
      </div>
    );
  }

  const { tracking, order } = info;
  const currentStatusIdx = tracking
    ? STATUSES.findIndex((s) => s.key === tracking.status)
    : -1;

  return (
    <>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css" crossOrigin="anonymous" />
      <div className="min-h-screen bg-[#0d1117] font-sans">
        {/* Header */}
        <div className="bg-gradient-to-r from-emerald-900/40 to-slate-900 border-b border-white/5 px-6 py-5">
          <div className="max-w-xl mx-auto">
            <p className="text-emerald-400 text-xs font-semibold uppercase tracking-widest mb-1">{order.business.name}</p>
            <h1 className="text-white text-2xl font-extrabold">Order #{order.orderNumber}</h1>
            <p className="text-gray-400 text-sm mt-0.5">Delivery tracking for {order.customerName}</p>
          </div>
        </div>

        <div className="max-w-xl mx-auto px-6 py-8 space-y-8">
          {/* Status Timeline */}
          <div className="bg-white/3 border border-white/8 rounded-2xl p-6">
            <h2 className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-6">Delivery Progress</h2>
            <div className="space-y-0">
              {STATUSES.map((step, idx) => {
                const isDone = currentStatusIdx >= idx;
                const isCurrent = currentStatusIdx === idx;
                const Icon = step.icon;
                return (
                  <div key={step.key} className="flex items-start gap-4">
                    <div className="flex flex-col items-center">
                      <div className={`h-9 w-9 rounded-full flex items-center justify-center border-2 transition-all ${
                        isDone
                          ? 'bg-emerald-500 border-emerald-500'
                          : 'bg-transparent border-white/10'
                      } ${isCurrent ? 'ring-4 ring-emerald-500/20' : ''}`}>
                        <Icon className={`h-4 w-4 ${isDone ? 'text-white' : 'text-gray-600'}`} />
                      </div>
                      {idx < STATUSES.length - 1 && (
                        <div className={`w-0.5 h-8 mt-1 ${isDone && currentStatusIdx > idx ? 'bg-emerald-500' : 'bg-white/10'}`} />
                      )}
                    </div>
                    <div className="pb-8 pt-1.5">
                      <p className={`text-sm font-bold ${isDone ? 'text-white' : 'text-gray-600'}`}>{step.label}</p>
                      {isCurrent && <p className="text-xs text-emerald-400 mt-0.5">{step.description}</p>}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Driver & ETA */}
          {tracking && (tracking.driverName || tracking.etaMinutes) && (
            <div className="bg-emerald-500/5 border border-emerald-500/20 rounded-2xl p-5 space-y-3">
              {tracking.driverName && (
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-full bg-emerald-500/20 flex items-center justify-center">
                    <Truck className="h-5 w-5 text-emerald-400" />
                  </div>
                  <div>
                    <p className="text-white font-semibold">{tracking.driverName}</p>
                    {tracking.driverPhone && <p className="text-gray-400 text-xs font-mono">{tracking.driverPhone}</p>}
                  </div>
                </div>
              )}
              {tracking.etaMinutes && (
                <div className="flex items-center gap-2 text-sm">
                  <Clock className="h-4 w-4 text-emerald-400" />
                  <span className="text-white">Estimated arrival in <strong>{tracking.etaMinutes} minutes</strong></span>
                </div>
              )}
              {tracking.notes && (
                <p className="text-xs text-gray-400 border-t border-white/5 pt-3">{tracking.notes}</p>
              )}
            </div>
          )}

          {/* Map */}
          {(tracking?.currentLat || order.deliveryLat) && (
            <div className="space-y-2">
              <h2 className="text-xs font-bold uppercase tracking-wider text-gray-400">Live Map</h2>
              <div ref={mapRef} style={{ height: '280px', width: '100%', borderRadius: '16px', overflow: 'hidden', zIndex: 1 }} className="border border-white/10" />
              <div className="flex gap-4 text-[10px] text-gray-400">
                <span className="flex items-center gap-1.5"><span className="inline-block h-2.5 w-2.5 rounded-full bg-emerald-500" />Driver</span>
                <span className="flex items-center gap-1.5"><span className="inline-block h-2.5 w-2.5 rounded-full bg-red-500" />Your Location</span>
              </div>
            </div>
          )}

          {/* Delivery Address */}
          {order.deliveryAddress && (
            <div className="bg-white/3 border border-white/8 rounded-xl p-4 flex items-start gap-3">
              <MapPin className="h-4 w-4 text-gray-400 mt-0.5 shrink-0" />
              <div>
                <p className="text-xs font-semibold uppercase tracking-wide text-gray-500 mb-0.5">Delivering To</p>
                <p className="text-white text-sm">{order.deliveryAddress}</p>
              </div>
            </div>
          )}

          <p className="text-center text-[10px] text-gray-600">Auto-refreshes every 30 seconds · Powered by {order.business.name}</p>
        </div>
      </div>
    </>
  );
}
