import { createFileRoute, Link, useParams } from "@tanstack/react-router";
import { useState } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Package,
  MapPin,
  CreditCard,
  User,
  ChevronRight,
  ArrowLeft,
  RotateCcw,
  Clock,
  Truck,
} from "lucide-react";
import { toast } from "sonner";
import { useStore, fmt, statusLabel, type OrderStatus } from "@/lib/store";

export const Route = createFileRoute("/admin/$id")({
  head: () => ({
    meta: [
      { title: "Admin — Order detail • SulejaMarket" },
      { name: "description", content: "Review order items, totals, customer and shipping details before updating status." },
    ],
  }),
  component: AdminOrderDetail,
});

const steps: OrderStatus[] = ["placed", "processing", "shipped", "out_for_delivery", "delivered"];

function AdminOrderDetail() {
  const { id } = useParams({ from: "/admin/$id" });
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const { orders, setOrderStatus, updateOrderDriverPhone, hydrated } = useStore();
  const order = orders.find((o) => o.id === id);

  const setStatus = (target: OrderStatus) => {
    if (!order) return;
    setOrderStatus(order.id, target);
    if (target === "delivered") {
      toast.success(`Order ${order.id} marked as DELIVERED! Customer payment released to vendor wallet.`);
    } else {
      toast.success(`Order ${order.id} status set to ${statusLabel[target]}`);
    }
  };

  const idx = order ? steps.indexOf(order.status) : -1;
  const next = order ? steps[idx + 1] : undefined;

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

      <main className="max-w-[1100px] mx-auto px-4 py-8">
        <Link to="/admin" className="text-sm text-orange-500 hover:underline inline-flex items-center gap-1 mb-4">
          <ArrowLeft className="w-4 h-4" /> Back to order management
        </Link>

        {!hydrated ? (
          <div className="text-center py-16 text-sm text-neutral-500">Loading…</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="/admin"><Button className="mt-5 bg-orange-500 hover:bg-orange-600">Back to admin</Button></Link>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Header card */}
            <div className="bg-white rounded-lg border p-6">
              <div className="flex flex-wrap items-start justify-between gap-4">
                <div>
                  <div className="text-xs text-neutral-500">Order</div>
                  <div className="flex items-center gap-2">
                    <h1 className="text-2xl font-bold">{order.id}</h1>
                    <span className="text-xs px-2 py-0.5 rounded-full bg-orange-100 text-orange-700 font-medium">
                      {statusLabel[order.status]}
                    </span>
                  </div>
                  <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">₦ {fmt(order.total)}</div>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-6">
              {/* Left: items + totals */}
              <div className="md:col-span-2 space-y-6">
                <div className="bg-white rounded-lg border">
                  <div className="px-5 py-3 border-b font-bold flex items-center gap-2">
                    <Package className="w-4 h-4 text-orange-500" /> Items ({order.items.length})
                  </div>
                  <div className="divide-y">
                    {order.items.map((it) => (
                      <div key={it.id} className="flex items-center gap-4 p-4">
                        <img src={(it.images?.[0] || `https://picsum.photos/seed/${it.seed}/80/80`)} alt={it.name} className="w-14 h-14 rounded object-cover" />
                        <div className="flex-1 min-w-0">
                          <div className="text-sm line-clamp-1">{it.name}</div>
                          <div className="text-xs text-neutral-500">Qty {it.qty} · ₦ {fmt(it.price)} each</div>
                        </div>
                        <div className="text-sm font-bold">₦ {fmt(it.price * it.qty)}</div>
                      </div>
                    ))}
                    <div className="p-4 space-y-1 text-sm bg-neutral-50">
                      <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 pt-1 border-t"><span>Total</span><span>₦ {fmt(order.total)}</span></div>
                    </div>
                  </div>
                </div>

                <div className="bg-white rounded-lg border">
                  <div className="px-5 py-3 border-b font-bold flex items-center gap-2">
                    <Clock className="w-4 h-4 text-orange-500" /> Status history
                  </div>
                  <div className="divide-y">
                    {order.history.map((h) => (
                      <div key={h.at} className="flex justify-between px-5 py-3 text-sm">
                        <span>{statusLabel[h.status]}</span>
                        <span className="text-neutral-500">{new Date(h.at).toLocaleString()}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Right: customer + shipping + payment + status controls */}
              <div className="space-y-6">
                <div className="bg-white rounded-lg border p-5">
                  <div className="font-bold mb-3 flex items-center gap-2"><User className="w-4 h-4 text-orange-500" /> Customer</div>
                  <div className="text-sm space-y-1">
                    <div className="font-medium">{order.address.name}</div>
                    <div className="text-neutral-500">{order.address.phone}</div>
                  </div>
                </div>

                <div className="bg-white rounded-lg border p-5">
                  <div className="font-bold mb-3 flex items-center gap-2"><MapPin className="w-4 h-4 text-orange-500" /> Shipping address</div>
                  <div className="text-sm text-neutral-600">
                    <div>{order.address.street}</div>
                    <div>{order.address.city}, {order.address.state}</div>
                  </div>
                </div>

                <div className="bg-white rounded-lg border p-5">
                  <div className="font-bold mb-3 flex items-center gap-2">
                    <Truck className="w-4 h-4 text-orange-500" /> Courier Driver Telemetry
                  </div>
                  <div className="text-sm space-y-3">
                    <div className="flex justify-between items-center">
                      <span className="text-neutral-500 text-xs">Assigned Driver Phone:</span>
                      {order.driverPhone ? (
                        <span className="font-mono font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 text-xs">
                          {order.driverPhone}
                        </span>
                      ) : (
                        <span className="text-amber-700 bg-amber-50 px-2 py-0.5 rounded border border-amber-200 text-[11px]">
                          Pending Assignment
                        </span>
                      )}
                    </div>
                    <form 
                      onSubmit={(e) => {
                        e.preventDefault();
                        const formData = new FormData(e.currentTarget);
                        const phone = (formData.get("driverPhone") as string || "").trim();
                        if (!/^\d{11}$/.test(phone)) {
                          toast.error("Driver phone number must be an 11-digit number (e.g. 08031234567)");
                          return;
                        }
                        updateOrderDriverPhone(order.id, phone);
                        toast.success(`Driver phone number (${phone}) updated by Admin!`);
                      }}
                      className="flex gap-2 pt-1 border-t"
                    >
                      <Input 
                        name="driverPhone"
                        defaultValue={order.driverPhone || ""} 
                        placeholder="11-digit phone (080...)"
                        maxLength={11}
                        className="h-8 text-xs font-mono"
                      />
                      <Button type="submit" size="sm" className="h-8 text-xs bg-neutral-900 hover:bg-neutral-800 text-white shrink-0">
                        Update Number
                      </Button>
                    </form>
                  </div>
                </div>

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

                <div className="bg-white rounded-lg border p-5">
                  <div className="font-bold mb-3">Admin Delivery & Payout Control</div>
                  {next ? (
                    <Button
                      className={next === 'delivered' ? "w-full bg-emerald-600 hover:bg-emerald-700 font-bold text-white shadow" : "w-full bg-orange-500 hover:bg-orange-600"}
                      onClick={() => setStatus(next)}
                    >
                      {next === 'delivered' ? "Confirm Delivery & Release Payout" : `Advance to ${statusLabel[next]}`} <ChevronRight className="w-4 h-4 ml-1" />
                    </Button>
                  ) : (
                    <Button className="w-full" variant="outline" disabled>
                      <RotateCcw className="w-3 h-3 mr-1" /> Order Delivered & Wallet Paid
                    </Button>
                  )}

                  <div className="flex flex-col gap-2 mt-4">
                    {steps.map((s, i) => {
                      const done = i <= idx;
                      const isCurrent = i === idx;
                      const isFuture = i > idx;
                      const isDeliveredStep = s === 'delivered';
                      return (
                        <button
                          key={s}
                          disabled={!isFuture}
                          onClick={() => setStatus(s)}
                          className={[
                            "text-xs px-3 py-2 rounded-md border text-left transition font-medium",
                            isCurrent && "bg-orange-500 text-white border-orange-500 font-bold",
                            done && !isCurrent && "bg-emerald-50 text-emerald-700 border-emerald-200",
                            isFuture && isDeliveredStep && "bg-emerald-600 text-white border-emerald-600 font-bold hover:bg-emerald-700 shadow-sm cursor-pointer",
                            isFuture && !isDeliveredStep && "bg-white text-neutral-700 border-neutral-300 hover:border-orange-400 hover:text-orange-600 cursor-pointer",
                          ].filter(Boolean).join(" ")}
                        >
                          {i + 1}. {statusLabel[s]} {isDeliveredStep ? "⚡ (Confirm Payout)" : ""}
                        </button>
                      );
                    })}
                  </div>

                  <Link to="/orders/$id" params={{ id: order.id }} className="block mt-4">
                    <Button variant="outline" className="w-full">View customer tracking</Button>
                  </Link>
                </div>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
