import { createFileRoute, Link, useParams } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { VideoReviewModal } from "@/components/site/VideoReviewModal";
import { LiveMapTracker } from "@/components/site/LiveMapTracker";
import { Button } from "@/components/ui/button";
import { Package, MapPin, CreditCard, Video, Sparkles } from "lucide-react";
import { useStore, fmt } from "@/lib/store";

export const Route = createFileRoute("/orders/$id")({
  head: () => ({ meta: [{ title: "Order tracking — SulejaMarket" }, { name: "description", content: "Track your order status in real time with live map GPS." }] }),
  component: OrderTracking,
});

function OrderTracking() {
  const { id } = useParams({ from: "/orders/$id" });
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [selectedReviewItem, setSelectedReviewItem] = useState<{ id: string; name: string } | null>(null);

  const { orders, hydrated } = useStore();
  const order = orders.find((o) => o.id === id);

  return (
    <div className="min-h-screen bg-neutral-50 pb-16">
      <SignInModal open={signInOpen} onOpenChange={setSignInOpen} />
      <CartDrawer open={cartOpen} onOpenChange={setCartOpen} onCheckout={() => { setCartOpen(false); setCheckoutOpen(true); }} />
      <CheckoutFlow open={checkoutOpen} onOpenChange={setCheckoutOpen} />

      {selectedReviewItem && order && (
        <VideoReviewModal
          open={!!selectedReviewItem}
          onOpenChange={(o) => { if (!o) setSelectedReviewItem(null); }}
          productId={selectedReviewItem.id}
          productName={selectedReviewItem.name}
          orderId={order.id}
        />
      )}

      <Header onOpenCart={() => setCartOpen(true)} onOpenSignIn={() => setSignInOpen(true)} />

      <main className="max-w-[960px] mx-auto px-4 py-6">
        {!hydrated ? (
          <div className="text-center py-16 text-sm text-neutral-500">Loading order telemetry…</div>
        ) : !order ? (
          <div className="bg-white rounded-lg border p-10 text-center">
            <Package className="w-12 h-12 text-neutral-300 mx-auto mb-3" />
            <h1 className="text-xl font-bold">Order not found</h1>
            <p className="text-sm text-neutral-500 mt-2">We couldn't find order {id}.</p>
            <Link to="/profile"><Button className="mt-5 bg-orange-500 hover:bg-orange-600">Back to my account</Button></Link>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Header info */}
            <div className="bg-white rounded-xl border p-6 flex flex-wrap items-center justify-between gap-4">
              <div>
                <div className="text-xs text-neutral-500 font-semibold uppercase tracking-wider">Order Details</div>
                <h1 className="text-2xl font-black text-neutral-900">{order.id}</h1>
                <div className="text-xs text-neutral-500 mt-1">Placed {new Date(order.createdAt).toLocaleString()}</div>
              </div>
              <div className="text-right">
                <div className="text-xs text-neutral-500">Total Paid</div>
                <div className="text-2xl font-bold text-orange-600">₦ {fmt(order.total)}</div>
              </div>
            </div>

            {/* Live GPS Order Milestone & Map Tracking */}
            <LiveMapTracker
              orderId={order.id}
              status={order.status}
              destinationAddress={order.address}
              driverPhone={order.driverPhone}
            />

            {/* Address & Payment Info */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="bg-white rounded-xl border p-5">
                <div className="font-bold mb-3 flex items-center gap-2 text-neutral-900">
                  <MapPin className="w-4 h-4 text-orange-500" /> Delivery Address
                </div>
                <div className="text-sm space-y-1">
                  <div className="font-semibold text-neutral-800">{order.address.name}</div>
                  <div className="text-neutral-600 text-xs">{order.address.phone}</div>
                  <div className="text-neutral-600 text-xs">{order.address.street}, {order.address.city}, {order.address.state}</div>
                </div>
              </div>

              <div className="bg-white rounded-xl border p-5">
                <div className="font-bold mb-3 flex items-center gap-2 text-neutral-900">
                  <CreditCard className="w-4 h-4 text-orange-500" /> Payment Telemetry
                </div>
                <div className="text-xs space-y-2">
                  <div className="flex justify-between"><span className="text-neutral-500">Method</span><span className="font-semibold">{order.paymentMethod}</span></div>
                  <div className="flex justify-between"><span className="text-neutral-500">Reference</span><span className="font-mono">{order.paymentRef}</span></div>
                  <div className="flex justify-between"><span className="text-neutral-500">Status</span><span className="text-emerald-600 font-bold">Verified Paid</span></div>
                </div>
              </div>
            </div>

            {/* Items List with Video Review Trigger for Delivered Items */}
            <div className="bg-white rounded-xl border overflow-hidden">
              <div className="px-5 py-4 border-b font-bold flex items-center justify-between">
                <span className="flex items-center gap-2 text-neutral-900">
                  <Package className="w-4 h-4 text-orange-500" /> Items in Package ({order.items.length})
                </span>
                {order.status === "delivered" && (
                  <span className="text-xs font-semibold text-emerald-600 flex items-center gap-1 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
                    <Sparkles className="w-3.5 h-3.5" /> Eligible for Video Review
                  </span>
                )}
              </div>

              <div className="divide-y divide-neutral-100">
                {order.items.map((it) => (
                  <div key={it.id} className="flex flex-wrap items-center gap-4 p-4 hover:bg-neutral-50/50 transition">
                    <img src={(it.images?.[0] || `https://picsum.photos/seed/${it.seed}/80/80`)} alt={it.name} className="w-16 h-16 rounded-lg object-cover border" />
                    <div className="flex-1 min-w-[200px]">
                      <div className="text-sm font-semibold text-neutral-900 line-clamp-1">{it.name}</div>
                      <div className="text-xs text-neutral-500 mt-0.5">Quantity: {it.qty}</div>
                    </div>

                    <div className="text-right">
                      <div className="text-sm font-bold text-neutral-900">₦ {fmt(it.price * it.qty)}</div>
                      
                      {/* Video Review Button when Delivered */}
                      {order.status === "delivered" ? (
                        <Button
                          size="sm"
                          onClick={() => setSelectedReviewItem({ id: it.id, name: it.name })}
                          className="mt-2 bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white text-xs gap-1.5 shadow-sm"
                        >
                          <Video className="w-3.5 h-3.5" /> Create Video Review
                        </Button>
                      ) : (
                        <div className="text-[11px] text-neutral-400 mt-1">Video review unlocks upon delivery</div>
                      )}
                    </div>
                  </div>
                ))}
              </div>

              <div className="p-4 space-y-1.5 text-xs bg-neutral-50 border-t">
                <div className="flex justify-between text-neutral-600"><span>Subtotal</span><span>₦ {fmt(order.subtotal)}</span></div>
                <div className="flex justify-between text-neutral-600"><span>Shipping</span><span>{order.shipping === 0 ? "Free" : `₦ ${fmt(order.shipping)}`}</span></div>
                <div className="flex justify-between text-neutral-600"><span>VAT (1%)</span><span>₦ {fmt(order.subtotal * 0.01)}</span></div>
                <div className="flex justify-between font-bold text-sm text-neutral-900 pt-1.5 border-t"><span>Total</span><span>₦ {fmt(order.total)}</span></div>
              </div>
            </div>

            <div className="pt-2">
              <Link to="/profile" className="text-sm font-medium text-orange-600 hover:underline">← Back to account orders</Link>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
