"use client";

import {
  ArrowUpRight,
  BadgeIndianRupee,
  Box,
  Check,
  ChevronDown,
  CircleUserRound,
  Eye,
  MoreHorizontal,
  PackagePlus,
  Search,
  ShoppingBag,
  Star,
  Store,
  TrendingUp,
  Upload,
  X,
} from "lucide-react";
import { FormEvent, useCallback, useEffect, useMemo, useState } from "react";
import { useTenant } from "@/components/tenant-provider";
import { products as catalog } from "@/lib/catalog";

type SellerProduct = {
  id: number | string;
  title: string;
  category: string;
  seller: string;
  price: string;
  originalPrice: string;
  image: string;
  rating: string;
  stock: number;
  active: boolean;
};

const demoInventory: SellerProduct[] = catalog.slice(0, 5).map((item, index) => ({
  id: item.id,
  title: item.name,
  category: item.category,
  seller: "Parsoni Demo Store",
  price: String(item.price),
  originalPrice: String(item.originalPrice),
  image: item.image,
  rating: String(item.rating),
  stock: [42, 18, 7, 24, 31][index],
  active: true,
}));

export default function SellerDashboard() {
  const { tenant, formatMoney } = useTenant();
  const [inventory, setInventory] = useState<SellerProduct[]>(demoInventory);
  const [query, setQuery] = useState("");
  const [modal, setModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [toast, setToast] = useState("");

  const loadProducts = useCallback(async () => {
    try {
      const response = await fetch("/api/products");
      const data = (await response.json()) as { products?: SellerProduct[] };
      if (data.products?.length) setInventory([...data.products, ...demoInventory]);
    } catch {
      // Demo inventory remains available if the network is unavailable.
    }
  }, []);

  useEffect(() => {
    void loadProducts();
  }, [loadProducts]);

  useEffect(() => {
    if (!toast) return;
    const timer = window.setTimeout(() => setToast(""), 2200);
    return () => window.clearTimeout(timer);
  }, [toast]);

  const visible = useMemo(() => {
    const term = query.toLowerCase();
    return inventory.filter((item) => item.title.toLowerCase().includes(term) || item.category.toLowerCase().includes(term));
  }, [inventory, query]);

  async function publish(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError("");
    const form = new FormData(event.currentTarget);
    try {
      const response = await fetch("/api/products", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(Object.fromEntries(form.entries())),
      });
      const data = (await response.json()) as { product?: SellerProduct; error?: string };
      if (!response.ok || !data.product) throw new Error(data.error || "Could not publish product");
      setInventory((items) => [data.product!, ...items]);
      setModal(false);
      setToast("Product published successfully");
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-[calc(100vh-72px)] bg-[#f4f7fb] px-4 py-7 sm:px-7">
      <div className="mx-auto max-w-7xl">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div><div className="flex items-center gap-2 text-xs font-black uppercase tracking-[0.15em] text-[#155ee9]"><Store size={14} /> Seller Centre</div><h1 className="mt-1 text-2xl font-black tracking-[-0.03em] sm:text-3xl">Welcome back, Demo Store</h1><p className="mt-1 text-xs text-slate-500">Manage products, orders and store performance.</p></div>
          <div className="flex items-center gap-2"><button onClick={() => setModal(true)} className="flex items-center gap-2 rounded-xl bg-[#155ee9] px-4 py-3 text-xs font-black text-white shadow-lg"><PackagePlus size={17} /> Add new product</button><button className="hidden items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-black sm:flex"><CircleUserRound size={18} className="text-[#155ee9]" /> Demo Store <ChevronDown size={13} /></button></div>
        </div>

        <section className="mt-7 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[
            [BadgeIndianRupee, "Total sales", formatMoney(184620), "+16.8%", "bg-blue-50 text-[#155ee9]"],
            [ShoppingBag, "Orders", "328", "+8.2%", "bg-violet-50 text-violet-600"],
            [Eye, "Product views", "24.8K", "+21.7%", "bg-orange-50 text-orange-600"],
            [Star, "Store rating", "4.7", "Top rated", "bg-green-50 text-green-600"],
          ].map(([Icon, label, value, change, style]) => { const CardIcon = Icon as React.ElementType; return <article key={String(label)} className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><div className="flex items-center justify-between"><span className={`grid h-10 w-10 place-items-center rounded-xl ${String(style)}`}><CardIcon size={19} /></span><span className="flex items-center gap-1 text-[9px] font-black text-green-600"><TrendingUp size={11} /> {String(change)}</span></div><p className="mt-4 text-2xl font-black">{String(value)}</p><p className="mt-1 text-xs font-bold text-slate-400">{String(label)}</p></article>; })}
        </section>

        <section className="mt-5 grid gap-5 lg:grid-cols-[1.35fr_0.65fr]">
          <article className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><div className="flex items-center justify-between"><div><h2 className="font-black">Sales performance</h2><p className="mt-1 text-[10px] text-slate-400">Revenue over the last 7 days</p></div><button className="rounded-lg border border-slate-200 px-3 py-2 text-[10px] font-bold">This week</button></div><div className="mt-6 flex h-36 items-end gap-3 border-b border-slate-100">{[45, 58, 39, 72, 61, 86, 95].map((height, index) => <div key={index} className="flex h-full flex-1 items-end justify-center"><div className="w-3/5 max-w-10 rounded-t-md bg-[#155ee9]" style={{ height: `${height}%`, opacity: 0.45 + index * 0.08 }} /></div>)}</div><div className="mt-3 flex justify-around text-[9px] font-bold text-slate-400">{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((day) => <span key={day}>{day}</span>)}</div></article>
          <article className="rounded-2xl bg-[#0b2756] p-5 text-white shadow-sm"><div className="flex items-start justify-between"><div><p className="text-xs font-black text-[#ffd54a]">SELLER TIP</p><h2 className="mt-2 text-xl font-black">You&apos;re close to Gold!</h2></div><span className="grid h-10 w-10 place-items-center rounded-xl bg-white/10">🏆</span></div><p className="mt-3 text-xs leading-5 text-blue-100">Ship 14 more orders on time this month to unlock lower commission and priority support.</p><div className="mt-6 h-2 overflow-hidden rounded-full bg-white/10"><div className="h-full w-[76%] rounded-full bg-[#ffd54a]" /></div><div className="mt-2 flex justify-between text-[9px] font-bold text-blue-200"><span>76% complete</span><span>14 orders left</span></div><button className="mt-6 flex items-center gap-2 text-xs font-black text-white">View performance <ArrowUpRight size={14} /></button></article>
        </section>

        <section className="mt-5 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
          <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-100 p-5"><div><h2 className="font-black">Your products</h2><p className="mt-1 text-[10px] text-slate-400">{inventory.length} listings in your catalogue</p></div><div className="flex gap-2"><div className="relative"><Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" /><input value={query} onChange={(event) => setQuery(event.target.value)} className="h-9 w-48 rounded-lg border border-slate-200 pl-9 pr-3 text-xs outline-none focus:border-blue-500 sm:w-64" placeholder="Search products" /></div><button onClick={() => setModal(true)} className="grid h-9 w-9 place-items-center rounded-lg bg-blue-50 text-[#155ee9] sm:hidden"><PackagePlus size={16} /></button></div></div>
          <div className="overflow-x-auto"><table className="w-full min-w-[760px] text-left"><thead><tr className="bg-slate-50 text-[9px] font-black uppercase tracking-wider text-slate-400"><th className="px-5 py-3">Product</th><th className="px-4 py-3">Category</th><th className="px-4 py-3">Price</th><th className="px-4 py-3">Stock</th><th className="px-4 py-3">Rating</th><th className="px-4 py-3">Status</th><th className="px-4 py-3" /></tr></thead><tbody className="divide-y divide-slate-100">{visible.map((product) => <tr key={String(product.id)} className="text-xs hover:bg-slate-50/70"><td className="px-5 py-3"><div className="flex items-center gap-3"><img src={product.image} alt="" className="h-12 w-12 rounded-xl bg-slate-100 object-cover" /><div><p className="max-w-[260px] truncate font-black">{product.title}</p><p className="mt-1 text-[9px] text-slate-400">SKU: PRS-{String(product.id).slice(-6).toUpperCase()}</p></div></div></td><td className="px-4 py-3 font-bold text-slate-500">{product.category}</td><td className="px-4 py-3"><p className="font-black">{formatMoney(Number(product.price))}</p><p className="mt-1 text-[9px] text-slate-400 line-through">{formatMoney(Number(product.originalPrice))}</p></td><td className="px-4 py-3"><p className={`font-black ${product.stock < 10 ? "text-orange-600" : "text-slate-700"}`}>{product.stock} units</p>{product.stock < 10 && <p className="mt-1 text-[9px] font-bold text-orange-500">Low stock</p>}</td><td className="px-4 py-3"><span className="flex items-center gap-1 font-black">{product.rating}<Star size={11} fill="#f4b521" className="text-[#f4b521]" /></span></td><td className="px-4 py-3"><span className="rounded-full bg-green-50 px-2 py-1 text-[9px] font-black text-green-700">Active</span></td><td className="px-4 py-3"><button className="p-2 text-slate-400"><MoreHorizontal size={17} /></button></td></tr>)}</tbody></table></div>
        </section>
      </div>

      {modal && <div className="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-[#071a3b]/60 p-4 backdrop-blur-sm"><button className="absolute inset-0" onClick={() => setModal(false)} aria-label="Close" /><div className="relative my-6 w-full max-w-xl rounded-3xl bg-white shadow-2xl"><div className="flex items-center justify-between border-b border-slate-100 p-5"><div><h2 className="text-lg font-black">Add a new product</h2><p className="mt-1 text-[10px] text-slate-400">Publish a product to your Parsoni catalogue</p></div><button onClick={() => setModal(false)} className="grid h-9 w-9 place-items-center rounded-full bg-slate-100"><X size={17} /></button></div><form onSubmit={publish} className="p-5"><div className="grid gap-4 sm:grid-cols-2"><label className="input-label sm:col-span-2">Product title *<input required name="title" className="checkout-input" placeholder="Enter a clear product name" /></label><label className="input-label">Vendor company / brand *<input required name="seller" defaultValue="Demo Store" className="checkout-input" /></label><label className="input-label">Category *<select required name="category" className="checkout-input"><option>Electronics</option><option>Fashion</option><option>Beauty</option><option>Home</option><option>Appliances</option><option>Toys</option></select></label><label className="input-label">Vendor email *<input required type="email" name="vendorEmail" defaultValue="seller@demostore.in" className="checkout-input" /></label><label className="input-label">Vendor phone *<input required type="tel" name="vendorPhone" defaultValue="+91 98765 43210" className="checkout-input" /></label><label className="input-label">GSTIN (optional)<input name="gstin" className="checkout-input uppercase" placeholder="09ABCDE1234F1Z5" /></label><label className="input-label">Cost price (₹)<input min="0" name="costPrice" type="number" className="checkout-input" placeholder="1200" /></label><label className="input-label">Selling price (₹) *<input required min="1" name="price" type="number" className="checkout-input" placeholder="1999" /></label><label className="input-label">MRP (₹) *<input required min="1" name="originalPrice" type="number" className="checkout-input" placeholder="2999" /></label><label className="input-label">Available stock *<input required min="0" name="stock" type="number" className="checkout-input" placeholder="50" /></label><label className="input-label">Product image URL *<input required name="image" type="url" className="checkout-input" placeholder="https://images.example.com/product.jpg" /></label><label className="input-label sm:col-span-2">Product description<textarea name="description" rows={3} className="checkout-input resize-none" placeholder="Describe material, features, warranty and included items" /></label></div><div className="mt-4 flex items-center gap-3 rounded-xl bg-blue-50 p-3"><Upload size={17} className="text-[#155ee9]" /><p className="text-[10px] leading-4 text-blue-800">Use a square, well-lit image URL for the best catalogue appearance.</p></div>{error && <p className="mt-4 rounded-xl bg-red-50 p-3 text-xs font-bold text-red-600">{error}</p>}<div className="mt-6 flex justify-end gap-2"><button type="button" onClick={() => setModal(false)} className="rounded-xl border border-slate-200 px-5 py-3 text-xs font-black">Cancel</button><button disabled={submitting} className="flex items-center gap-2 rounded-xl bg-[#155ee9] px-5 py-3 text-xs font-black text-white disabled:opacity-60">{submitting ? "Publishing…" : "Publish product"}<Check size={15} /></button></div></form></div></div>}
      {toast && <div className="fixed bottom-6 left-1/2 z-[70] flex -translate-x-1/2 items-center gap-2 rounded-xl bg-[#101d37] px-5 py-3 text-xs font-bold text-white shadow-2xl"><Check size={15} className="text-green-400" />{toast}</div>}
    </main>
  );
}
