import { useState, useEffect } from "react";
import { MapPin, Navigation, Truck, CheckCircle2, Phone, Clock, ShieldCheck, Compass, Radio } from "lucide-react";
import { Button } from "@/components/ui/button";
import { type OrderStatus } from "@/lib/store";
import { toast } from "sonner";

interface LiveMapTrackerProps {
  orderId: string;
  status: OrderStatus;
  destinationAddress: {
    name: string;
    street: string;
    city: string;
    state: string;
  };
  vendorName?: string;
  driverPhone?: string;
}

const stepsList: { key: OrderStatus; label: string; desc: string }[] = [
  { key: "placed", label: "Order Confirmed", desc: "Received by SulejaMarket" },
  { key: "processing", label: "Packed at Store", desc: "Vendor prepared package" },
  { key: "shipped", label: "In Transit", desc: "Dispatched from Suleja Hub" },
  { key: "out_for_delivery", label: "Out for Delivery", desc: "Courier driver en-route" },
  { key: "delivered", label: "Delivered", desc: "Package handed over" },
];

export function LiveMapTracker({ orderId, status, destinationAddress, vendorName = "Suleja Central Vendor Store", driverPhone }: LiveMapTrackerProps) {
  const currentStepIdx = stepsList.findIndex((s) => s.key === status);
  const isDelivered = status === "delivered";

  // Base progress percentage corresponding to each vendor-managed status
  const baseProgressMap: Record<OrderStatus, number> = {
    placed: 5,
    processing: 25,
    shipped: 55,
    out_for_delivery: 85,
    delivered: 100,
  };

  const etaMap: Record<OrderStatus, number> = {
    placed: 40,
    processing: 28,
    shipped: 18,
    out_for_delivery: 7,
    delivered: 0,
  };

  const baseProgress = baseProgressMap[status] ?? 0;
  const etaMinutes = etaMap[status] ?? 0;

  // Add subtle micro-telemetry animation (+/- 1.5%) around the vendor-controlled milestone position
  const [telemetryOffset, setTelemetryOffset] = useState<number>(0);

  useEffect(() => {
    if (isDelivered || status === "placed") {
      setTelemetryOffset(0);
      return;
    }

    const interval = setInterval(() => {
      setTelemetryOffset((prev) => (prev === 0 ? 1.5 : prev === 1.5 ? -1.5 : 0));
    }, 2500);

    return () => clearInterval(interval);
  }, [isDelivered, status]);

  const driverProgress = Math.min(100, Math.max(0, baseProgress + telemetryOffset));

  return (
    <div className="bg-white rounded-xl border border-neutral-200 overflow-hidden shadow-sm">
      {/* Top Banner Status */}
      <div className="bg-gradient-to-r from-neutral-900 via-neutral-800 to-neutral-900 text-white p-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-orange-500/20 border border-orange-500/50 flex items-center justify-center text-orange-400">
            <Radio className="w-5 h-5 animate-pulse" />
          </div>
          <div>
            <div className="text-xs text-neutral-400 uppercase tracking-wider font-semibold flex items-center gap-1.5">
              <span>Live GPS Milestone Dispatch</span>
              <span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-400 font-normal border border-emerald-500/30">
                Vendor Controlled
              </span>
            </div>
            <div className="text-base font-bold flex items-center gap-2">
              Order {orderId}
              <span className="text-xs px-2.5 py-0.5 rounded-full font-medium bg-orange-500 text-white">
                {status.replace(/_/g, " ").toUpperCase()}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Interactive Map Visualizer */}
      <div className="relative bg-slate-900 h-[260px] sm:h-[300px] overflow-hidden select-none">
        {/* Map Grid Pattern background */}
        <div
          className="absolute inset-0 opacity-20"
          style={{
            backgroundImage: `radial-gradient(#38bdf8 1px, transparent 1px)`,
            backgroundSize: "24px 24px",
          }}
        />

        {/* Map Vector Path */}
        <svg className="absolute inset-0 w-full h-full" viewBox="0 0 600 240" preserveAspectRatio="none">
          {/* Main Highway Route */}
          <path
            d="M 80,120 Q 300,40 520,120"
            fill="none"
            stroke="#334155"
            strokeWidth="8"
            strokeLinecap="round"
          />
          <path
            d="M 80,120 Q 300,40 520,120"
            fill="none"
            stroke="#f97316"
            strokeWidth="4"
            strokeDasharray="8 6"
            strokeLinecap="round"
            className="animate-pulse"
          />

          {/* Start Hub Pin */}
          <g transform="translate(80, 120)">
            <circle r="14" fill="#f97316" fillOpacity="0.3" className="animate-ping" />
            <circle r="8" fill="#f97316" />
          </g>

          {/* Destination Pin */}
          <g transform="translate(520, 120)">
            <circle r="14" fill="#10b981" fillOpacity="0.3" className="animate-ping" />
            <circle r="8" fill="#10b981" />
          </g>
        </svg>

        {/* Start Hub Label Overlay */}
        <div className="absolute left-4 top-16 bg-slate-800/90 backdrop-blur-md border border-slate-700 text-white p-2.5 rounded-lg text-xs shadow-lg max-w-[150px]">
          <div className="text-[10px] text-orange-400 font-bold uppercase flex items-center gap-1">
            <Compass className="w-3 h-3" /> Vendor Hub
          </div>
          <div className="font-semibold truncate">{vendorName}</div>
          <div className="text-[10px] text-slate-400">Suleja, Niger State</div>
        </div>

        {/* Destination Label Overlay */}
        <div className="absolute right-4 bottom-12 bg-slate-800/90 backdrop-blur-md border border-slate-700 text-white p-2.5 rounded-lg text-xs shadow-lg max-w-[170px]">
          <div className="text-[10px] text-emerald-400 font-bold uppercase flex items-center gap-1">
            <MapPin className="w-3 h-3" /> Delivery Address
          </div>
          <div className="font-semibold truncate">{destinationAddress.name}</div>
          <div className="text-[10px] text-slate-400 truncate">{destinationAddress.street}, {destinationAddress.city}</div>
        </div>

        {/* Live Moving Courier Driver Marker */}
        <div
          className="absolute transform -translate-x-1/2 -translate-y-1/2 transition-all duration-1000 ease-out z-20"
          style={{
            left: `${Math.min(92, Math.max(12, (driverProgress / 100) * 82 + 10))}%`,
            top: `${50 - Math.sin((driverProgress / 100) * Math.PI) * 20}%`,
          }}
        >
          <div className="relative group">
            <div className="w-11 h-11 rounded-full bg-orange-500 text-white flex items-center justify-center shadow-xl ring-4 ring-orange-500/30">
              <Truck className="w-6 h-6" />
            </div>

            {/* Courier Tooltip */}
            <div className="absolute -top-12 left-1/2 -translate-x-1/2 bg-neutral-900 text-white text-[11px] px-2.5 py-1 rounded-md whitespace-nowrap shadow-xl border border-neutral-700 flex items-center gap-1.5 font-medium">
              <span className="w-2 h-2 rounded-full bg-emerald-400 animate-ping" />
              Suleja Express Courier ({driverProgress}%)
            </div>
          </div>
        </div>

        {/* Live GPS Telemetry Bar */}
        <div className="absolute bottom-3 left-4 right-4 bg-slate-900/90 backdrop-blur-md border border-slate-800 rounded-lg p-2 text-[11px] text-slate-300 flex flex-wrap items-center justify-between gap-2">
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-1.5">
              <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
              <span>GPS: <strong className="text-white font-mono">9.1804° N, 7.1793° E</strong></span>
            </div>
            {driverPhone && (
              <span className="text-emerald-400 font-mono text-[11px] bg-slate-800 px-2 py-0.5 rounded border border-slate-700">
                Driver: <strong>{driverPhone}</strong>
              </span>
            )}
          </div>
          <div className="flex items-center gap-3">
            <Button
              size="sm"
              variant="secondary"
              onClick={() => {
                if (driverPhone) {
                  toast.info(`Contacting Driver (${driverPhone})...`);
                  window.location.href = `tel:${driverPhone}`;
                } else {
                  toast.warning("The vendor has not assigned a driver phone number yet.");
                }
              }}
              className="h-7 text-[11px] gap-1 bg-orange-500 hover:bg-orange-600 text-white font-semibold"
            >
              <Phone className="w-3 h-3" /> Call Driver {driverPhone ? `(${driverPhone})` : ""}
            </Button>
          </div>
        </div>
      </div>

      {/* Milestone Progress Stepper */}
      <div className="p-6 bg-white border-t">
        <h4 className="text-xs font-bold text-neutral-500 uppercase tracking-wider mb-4">Milestone Checkpoints</h4>
        <div className="grid grid-cols-1 sm:grid-cols-5 gap-4 relative">
          {stepsList.map((step, idx) => {
            const completed = currentStepIdx >= idx;
            const isCurrent = currentStepIdx === idx;
            return (
              <div key={step.key} className="flex sm:flex-col items-center sm:text-center gap-3 sm:gap-2">
                <div
                  className={`w-9 h-9 rounded-full flex items-center justify-center shrink-0 text-xs font-bold transition-all ${
                    completed
                      ? "bg-orange-500 text-white shadow-md shadow-orange-500/20"
                      : "bg-neutral-100 text-neutral-400 border border-neutral-200"
                  } ${isCurrent ? "ring-4 ring-orange-100 scale-110" : ""}`}
                >
                  {completed ? <CheckCircle2 className="w-5 h-5" /> : idx + 1}
                </div>
                <div>
                  <div className={`text-xs font-bold ${completed ? "text-neutral-900" : "text-neutral-400"}`}>
                    {step.label}
                  </div>
                  <div className="text-[10px] text-neutral-500 line-clamp-1">{step.desc}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
