import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Store, Package, Trash2 } from "lucide-react";
import { useStore, fmt } from "@/lib/store";

export const Route = createFileRoute("/admin_/vendors/$id")({
  head: () => ({ meta: [{ title: "Vendor Dashboard (Admin View) — SulejaMarket" }] }),
  component: AdminVendorPage,
});

function AdminVendorPage() {
  const { id } = Route.useParams();
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  
  const { vendors } = useStore();
  const vendor = vendors.find(v => v.id === id);

  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">
        {!vendor ? (
          <div className="text-center py-20 text-neutral-500">Vendor not found</div>
        ) : (
          <AdminVendorDashboard vendorEmail={vendor.contactEmail} vendorName={vendor.contactName} businessName={vendor.businessName} />
        )}
      </main>
    </div>
  );
}

function AdminVendorDashboard({ vendorEmail, vendorName, businessName }: { vendorEmail: string, vendorName: string, businessName: string }) {
  const { vendorProducts, removeProduct } = useStore();
  const mine = vendorProducts.filter((p) => p.vendorEmail === vendorEmail);

  return (
    <div className="space-y-6">
      <div className="flex items-end justify-between">
        <div>
          <div className="text-xs text-neutral-500 mb-1 flex items-center gap-1">
            <Link to="/admin" className="hover:underline">Admin</Link>
            <span>/</span>
            <span>Vendors</span>
          </div>
          <h1 className="text-2xl font-bold flex items-center gap-2"><Store className="w-6 h-6 text-orange-500" /> {businessName} (Admin View)</h1>
          <p className="text-sm text-neutral-500">Managing products for {vendorName}. Active listings: {mine.length}.</p>
        </div>
        <div className="flex gap-3">
          <Stat label="Listings" value={String(mine.length)} />
          <Stat label="Status" value="Active" tone="emerald" />
        </div>
      </div>

      <div className="grid grid-cols-3 gap-6">
        <div className="col-span-3 bg-white rounded-lg border">
          <div className="px-5 py-3 border-b font-bold flex items-center justify-between">
            <div className="flex items-center gap-2"><Package className="w-4 h-4" /> Listings</div>
          </div>
          {mine.length === 0 ? (
            <div className="p-10 text-center text-sm text-neutral-500">No products yet.</div>
          ) : (
            <div className="divide-y">
              {mine.map((p) => (
                <div key={p.id} className="flex items-center gap-4 p-4">
                  <img src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/80/80`)} alt={p.name} className="w-14 h-14 rounded object-cover" />
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium line-clamp-1">{p.name}</div>
                    <div className="text-xs text-neutral-500">{p.category}</div>
                  </div>
                  <div className="text-sm font-bold">₦ {fmt(p.price)}</div>
                  <button onClick={() => { if(confirm("Delete this product?")) removeProduct(p.id) }} className="text-neutral-400 hover:text-red-500">
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Stat({ label, value, tone }: { label: string; value: string; tone?: "emerald" }) {
  return (
    <div className={`px-4 py-2 rounded-md border ${tone === "emerald" ? "bg-emerald-50 border-emerald-200 text-emerald-700" : "bg-white"}`}>
      <div className="text-[10px] uppercase tracking-wide text-neutral-500">{label}</div>
      <div className="font-bold text-sm">{value}</div>
    </div>
  );
}
