import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ImageUpload } from "@/components/ui/image-upload";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Store, ArrowRight, CheckCircle2, ShoppingCart, MapPin, Building2, Map, Package, Plus, Trash2, Clock, ShieldCheck, BadgeCheck, Wallet, Truck, Coins, Sparkles, Flame, Award, History } from "lucide-react";
import { usePaystackPayment } from "react-paystack";
import { toast } from "sonner";
import { useStore, fmt } from "@/lib/store";
import { CATEGORIES } from "@/lib/categories";

import { TawkChatWidget } from "@/components/site/TawkChatWidget";

export const Route = createFileRoute("/vendor")({
  head: () => ({ meta: [{ title: "Vendor Dashboard — SulejaMarket" }, { name: "description", content: "Manage your SulejaMarket storefront and product listings." }] }),
  component: VendorPage,
});

function VendorPage() {
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const { user, signIn, applyVendor } = useStore();

  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">
        {(!user || user.role === "customer") && <ApplyPanel onApply={(profile) => { if (!user) signIn(profile.contactEmail, profile.contactName); applyVendor(profile); toast.success("Application submitted!"); }} />}
        {user && user.role === "pending_vendor" && <PendingPanel />}
        {user && user.role === "vendor" && <VendorDashboard />}
      </main>

      {/* Vendor <-> Admin Tawk.to AI Chat Channel */}
      <TawkChatWidget channel="vendor-admin" />
    </div>
  );
}

function SignedOut({ onSignIn }: { onSignIn: () => void }) {
  return (
    <div className="bg-white rounded-lg border p-10 text-center">
      <Store className="w-12 h-12 text-orange-500 mx-auto mb-3" />
      <h1 className="text-2xl font-bold">Sign in to become a vendor</h1>
      <p className="text-sm text-neutral-500 mt-2">You need an account before you can list products.</p>
      <Button onClick={onSignIn} className="mt-5 bg-orange-500 hover:bg-orange-600">Sign in</Button>
    </div>
  );
}

const Field = ({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) => (
  <div><label className="text-xs font-medium">{label}{required && " *"}</label>{children}</div>
);

function ApplyPanel({ onApply }: { onApply: (profile: any) => void }) {
  const [form, setForm] = useState({
    businessName: "", businessType: "", category: "", rcNumber: "", taxId: "",
    contactName: "", contactEmail: "", contactPhone: "", altPhone: "",
    address: "", city: "", state: "", country: "Nigeria",
    lat: undefined as number | undefined,
    lng: undefined as number | undefined,
    website: "", productInfo: "",
    bankName: "", accountName: "", accountNumber: "",
    agree: false, marketing: false,
  });
  const set = (k: keyof typeof form, v: any) => setForm((f) => ({ ...f, [k]: v }));

  const getLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((pos) => {
        set("lat", pos.coords.latitude);
        set("lng", pos.coords.longitude);
      }, () => toast.error("Location access denied."));
    }
  };

  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.agree) { toast.error("Please accept the Seller Terms"); return; }
    if (form.accountNumber && !/^\d{10}$/.test(form.accountNumber)) {
      toast.error("Account number must be 10 digits"); return;
    }
    // @ts-ignore
    onApply({ ...form });
  };

  return (
    <div className="bg-white rounded-lg border p-8 max-w-3xl mx-auto">
      <div className="flex items-center gap-2 mb-1"><Store className="w-6 h-6 text-orange-500" /><span className="text-lg font-extrabold">Become a SulejaMarket Seller</span></div>
      <h1 className="text-2xl font-bold">Vendor registration</h1>
      <p className="text-sm text-neutral-500 mb-6">Reach millions of shoppers. Applications are reviewed within 48 hours.</p>

      <form className="space-y-6" onSubmit={submit}>
        <section className="space-y-3">
          <h2 className="text-sm font-bold text-neutral-700 border-b pb-1">1. Business details</h2>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Business name" required>
              <Input required value={form.businessName} onChange={(e) => set("businessName", e.target.value)} placeholder="Acme Traders Ltd" />
            </Field>
            <Field label="Business type" required>
              <Select value={form.businessType} onValueChange={(v) => set("businessType", v)} required>
                <SelectTrigger><SelectValue placeholder="Select type" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="individual">Individual / Sole trader</SelectItem>
                  <SelectItem value="registered">Registered company (LTD)</SelectItem>
                  <SelectItem value="manufacturer">Manufacturer</SelectItem>
                  <SelectItem value="distributor">Distributor / Wholesaler</SelectItem>
                </SelectContent>
              </Select>
            </Field>
            <Field label="Primary category" required>
              <Select value={form.category} onValueChange={(v) => set("category", v)} required>
                <SelectTrigger><SelectValue placeholder="Select category" /></SelectTrigger>
                <SelectContent>
                  {["Phones & Tablets", "Electronics", "Fashion", "Home & Office", "Health & Beauty", "Groceries", "Other"].map((c) => (
                    <SelectItem key={c} value={c}>{c}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field label="Website / social handle">
              <Input value={form.website} onChange={(e) => set("website", e.target.value)} placeholder="https:// or @handle" />
            </Field>
            <Field label="CAC / RC number">
              <Input value={form.rcNumber} onChange={(e) => set("rcNumber", e.target.value)} placeholder="RC 1234567" />
            </Field>
            <Field label="Tax Identification Number (TIN)">
              <Input value={form.taxId} onChange={(e) => set("taxId", e.target.value)} placeholder="12345678-0001" />
            </Field>
          </div>
        </section>

        <section className="space-y-3">
          <h2 className="text-sm font-bold text-neutral-700 border-b pb-1">2. Contact person</h2>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Full name" required>
              <Input required value={form.contactName} onChange={(e) => set("contactName", e.target.value)} placeholder="Jane Doe" />
            </Field>
            <Field label="Email address" required>
              <Input required type="email" value={form.contactEmail} onChange={(e) => set("contactEmail", e.target.value)} placeholder="you@business.com" />
            </Field>
            <Field label="Phone number" required>
              <Input required type="tel" value={form.contactPhone} onChange={(e) => set("contactPhone", e.target.value)} placeholder="0810 000 0000" />
            </Field>
            <Field label="Alternative phone">
              <Input type="tel" value={form.altPhone} onChange={(e) => set("altPhone", e.target.value)} placeholder="Optional" />
            </Field>
          </div>
        </section>

        <section className="space-y-3">
          <h2 className="text-sm font-bold text-neutral-700 border-b pb-1">3. Warehouse / pickup address</h2>
          <Field label="Street address" required>
            <Textarea required rows={2} value={form.address} onChange={(e) => set("address", e.target.value)} placeholder="No. 12, Market Road" />
          </Field>
          <div className="grid grid-cols-3 gap-3">
            <Field label="City" required>
              <Input required value={form.city} onChange={(e) => set("city", e.target.value)} placeholder="Suleja" />
            </Field>
            <Field label="State" required>
              <Input required value={form.state} onChange={(e) => set("state", e.target.value)} placeholder="Niger" />
            </Field>
            <Field label="Country" required>
              <Input required value={form.country} onChange={(e) => set("country", e.target.value)} />
            </Field>
          </div>
          <div className="pt-2">
            <div className="flex items-center justify-between bg-neutral-50 p-3 rounded-lg border">
              <div className="text-sm">
                <p className="font-medium text-neutral-700 mb-0.5">Exact Shop Coordinates</p>
                {form.lat && form.lng ? (
                  <p className="text-emerald-600 text-xs">Captured: {form.lat.toFixed(6)}, {form.lng.toFixed(6)}</p>
                ) : (
                  <p className="text-neutral-500 text-xs">Recommended to help customers and delivery riders find your shop easily.</p>
                )}
              </div>
              <Button type="button" variant="outline" size="sm" onClick={getLocation} className="shrink-0 gap-1.5 border-orange-200 text-orange-600 hover:bg-orange-50 hover:text-orange-700">
                <MapPin className="w-4 h-4" />
                {form.lat ? "Update Location" : "Get My Location"}
              </Button>
            </div>
          </div>
        </section>

        <section className="space-y-3">
          <h2 className="text-sm font-bold text-neutral-700 border-b pb-1">4. Payout details</h2>
          <div className="grid grid-cols-3 gap-3">
            <Field label="Bank name" required>
              <Input required value={form.bankName} onChange={(e) => set("bankName", e.target.value)} placeholder="GTBank" />
            </Field>
            <Field label="Account name" required>
              <Input required value={form.accountName} onChange={(e) => set("accountName", e.target.value)} placeholder="Acme Traders Ltd" />
            </Field>
            <Field label="Account number" required>
              <Input required inputMode="numeric" maxLength={10} value={form.accountNumber} onChange={(e) => set("accountNumber", e.target.value.replace(/\D/g, ""))} placeholder="0123456789" />
            </Field>
          </div>
        </section>

        <section className="space-y-3">
          <h2 className="text-sm font-bold text-neutral-700 border-b pb-1">5. About your products</h2>
          <Field label="Brands, SKUs, monthly volume">
            <Textarea rows={3} value={form.productInfo} onChange={(e) => set("productInfo", e.target.value)} placeholder="e.g. 200+ SKUs of fashion accessories, ~500 orders/month" />
          </Field>
        </section>

        <div className="space-y-2 pt-2 border-t">
          <label className="flex items-start gap-2 text-xs text-neutral-600">
            <input type="checkbox" required checked={form.agree} onChange={(e) => set("agree", e.target.checked)} className="mt-0.5 accent-orange-500" />
            <span>I confirm the information above is accurate and agree to the SulejaMarket Seller Terms & Commission Schedule.</span>
          </label>
          <label className="flex items-start gap-2 text-xs text-neutral-600">
            <input type="checkbox" checked={form.marketing} onChange={(e) => set("marketing", e.target.checked)} className="mt-0.5 accent-orange-500" />
            <span>Send me seller tips, promo opportunities and platform updates.</span>
          </label>
        </div>

        <div className="flex items-center justify-between pt-2">
          <p className="text-xs text-neutral-400">Your application is reviewed within 24-48 hours.</p>
          <Button type="submit" className="bg-orange-500 hover:bg-orange-600 h-11 px-8">Submit application</Button>
        </div>
      </form>
    </div>
  );
}

function PendingPanel() {
  return (
    <div className="bg-white rounded-lg border p-10 text-center max-w-xl mx-auto">
      <Clock className="w-12 h-12 text-amber-500 mx-auto mb-3" />
      <h1 className="text-2xl font-bold">Application under review</h1>
      <p className="text-sm text-neutral-500 mt-2 mb-6">Our seller team is verifying your details. This usually takes 24-48 hours.</p>
    </div>
  );
}

function VendorDriverPhoneForm({ orderId, currentPhone, onSave }: { orderId: string; currentPhone?: string; onSave: (id: string, phone: string) => void }) {
  const [phone, setPhone] = useState(currentPhone || "");

  useEffect(() => {
    if (currentPhone) setPhone(currentPhone);
  }, [currentPhone]);

  const handleSave = (e: React.FormEvent) => {
    e.preventDefault();
    const cleanPhone = phone.trim();
    if (!/^\d{11}$/.test(cleanPhone)) {
      toast.error("Driver phone number must be an 11-digit number (e.g. 08031234567)");
      return;
    }
    onSave(orderId, cleanPhone);
    toast.success(`Driver phone number (${cleanPhone}) assigned to Order ${orderId}!`);
  };

  return (
    <form onSubmit={handleSave} className="bg-white p-3 rounded-lg border space-y-2">
      <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2">
        <label className="text-xs font-bold text-neutral-800 flex items-center gap-1.5">
          <Truck className="w-4 h-4 text-orange-500" /> Assign Driver Call Number (11 Digits):
        </label>
        {currentPhone ? (
          <span className="text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 self-start sm:self-auto font-mono">
            Active: {currentPhone}
          </span>
        ) : (
          <span className="text-[10px] text-amber-700 bg-amber-50 px-2 py-0.5 rounded border border-amber-200 self-start sm:self-auto">
            Not assigned yet
          </span>
        )}
      </div>

      <div className="flex gap-2">
        <Input 
          value={phone} 
          onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))} 
          placeholder="Enter 11-digit phone number (e.g. 08031234567)" 
          maxLength={11} 
          required
          className="h-8 text-xs font-mono bg-neutral-50" 
        />
        <Button type="submit" size="sm" className="h-8 text-xs bg-neutral-900 hover:bg-neutral-800 text-white shrink-0 font-semibold px-4">
          Save Driver Number
        </Button>
      </div>
    </form>
  );
}

function VendorDashboard() {
  const { vendorProducts, addProduct, editProduct, removeProduct, user, vendors, paystackKey, verifyVendor, editVendorProfile, orders, setOrderStatus, updateOrderDriverPhone, withdrawals, fetchWithdrawals, requestWithdrawal, fetchLoyaltyData, featureProductWithLoyalty } = useStore();
  const mine = vendorProducts.filter((p) => p.vendorEmail === user?.email);
  const myVendorProfile = vendors.find(v => v.contactEmail === user?.email);
  const [loyaltyTransactions, setLoyaltyTransactions] = useState<any[]>([]);

  const loadLoyalty = () => {
    if (user?.email) {
      fetchLoyaltyData(user.email).then((res) => {
        setLoyaltyTransactions(res.transactions || []);
      });
    }
  };
  
  useEffect(() => {
    if (user?.email) {
      fetchWithdrawals(user.email);
      loadLoyalty();
    }
  }, [user?.email, fetchWithdrawals]);
  
  const myOrders = orders.filter(o => o.items.some(item => vendorProducts.some(p => p.id === item.id && p.vendorEmail === user?.email)));
  
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<{ 
    name: string; price: string; old: string; category: string;
    summary: string; description: string; 
    img1: string; img2: string; img3: string;
    colors: string; sizes: string;
    is_top: boolean;
  }>({ 
    name: "", price: "", old: "", category: "",
    summary: "", description: "", 
    img1: "", img2: "", img3: "",
    colors: "", sizes: "",
    is_top: false
  });

  const paystackConfig = {
    reference: `VERIFY_${Math.random().toString(36).slice(2, 10).toUpperCase()}`,
    email: user?.email || "vendor@example.com",
    amount: 1000 * 100, // 1000 Naira in kobo
    publicKey: paystackKey,
  };
  const initializePayment = usePaystackPayment(paystackConfig);

  const handleVerify = () => {
    if (!paystackKey) {
      toast.error("Payments are currently unavailable (missing API key).");
      return;
    }
    initializePayment({
      onSuccess: () => {
        if (myVendorProfile) {
          verifyVendor(myVendorProfile.id);
          toast.success("Congratulations! You are now a verified vendor.");
        }
      },
      onClose: () => {
        toast("Payment cancelled.");
      }
    });
  };

  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    const price = Number(form.price);
    if (!form.name || !price) return;
    const images = [form.img1, form.img2, form.img3].filter(Boolean);
    
    const payload = {
      name: form.name,
      price,
      old: form.old ? Number(form.old) : undefined,
      disc: form.old ? `-${Math.round((1 - price / Number(form.old)) * 100)}%` : undefined,
      category: form.category || "Other",
      summary: form.summary || undefined,
      description: form.description || undefined,
      images: images.length > 0 ? images : undefined,
      colors: form.colors ? form.colors.split(",").map(s => s.trim()).filter(Boolean) : undefined,
      sizes: form.sizes ? form.sizes.split(",").map(s => s.trim()).filter(Boolean) : undefined,
      is_top: form.is_top,
    };

    if (editingId) {
      editProduct(editingId, payload);
      toast.success("Product updated", { description: form.name });
      setEditingId(null);
    } else {
      addProduct(payload);
      toast.success("Product listed", { description: form.name });
    }
    setForm({ name: "", price: "", old: "", category: "", summary: "", description: "", img1: "", img2: "", img3: "", colors: "", sizes: "", is_top: false });
  };

  const handleEdit = (p: any) => {
    setEditingId(p.id);
    setForm({
      name: p.name,
      price: String(p.price),
      old: p.old ? String(p.old) : "",
      category: p.category || "",
      summary: p.summary || "",
      description: p.description || "",
      img1: p.images?.[0] || "",
      img2: p.images?.[1] || "",
      img3: p.images?.[2] || "",
      colors: p.colors ? p.colors.join(", ") : "",
      sizes: p.sizes ? p.sizes.join(", ") : "",
      is_top: !!p.is_top
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleFeature = async (p: any) => {
    const currentCoins = myVendorProfile?.loyalty_coins || 0;
    if (currentCoins < 100) {
      toast.error("Insufficient Loyalty Coins! Deliver customer orders to earn 100 coins per completed sale.");
      return;
    }

    if (confirm(`Spend 100 Loyalty Coins to feature '${p.name}' across SulejaMarket?`)) {
      const res = await featureProductWithLoyalty(user!.email, p.id);
      if (res.success) {
        toast.success(`✨ '${p.name}' is now a Featured Product across SulejaMarket!`);
        loadLoyalty();
      } else {
        toast.error(res.error || "Failed to feature product.");
      }
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Store className="w-6 h-6 text-orange-500" /> 
            Vendor Dashboard
            {myVendorProfile?.is_verified && <span className="inline-flex"><BadgeCheck className="w-5 h-5 text-sky-500" /></span>}
          </h1>
          <p className="text-sm text-neutral-500">Welcome back, {user?.name}. You have {mine.length} active listing{mine.length === 1 ? "" : "s"}.</p>
          {myVendorProfile?.storeSlug && (
            <div className="mt-2 text-sm">
              <span className="text-neutral-500 mr-2">Your Storefront URL:</span>
              <a href={`/${myVendorProfile.storeSlug}`} target="_blank" rel="noreferrer" className="text-orange-500 font-medium hover:underline inline-flex items-center gap-1">
                sulejamarket.com/{myVendorProfile.storeSlug}
              </a>
            </div>
          )}
        </div>
        <div className="flex gap-3 items-center">
          {!myVendorProfile?.is_verified && (
            <Button onClick={handleVerify} className="bg-sky-500 hover:bg-sky-600">
              <BadgeCheck className="w-4 h-4 mr-2" /> Get Verified (₦1,000)
            </Button>
          )}
          <Stat label="Listings" value={String(mine.length)} />
          <Stat label="Loyalty Coins" value={`🪙 ${myVendorProfile?.loyalty_coins || 0}`} tone="emerald" />
        </div>
      </div>

      {myVendorProfile && (
        <StoreCustomization profile={myVendorProfile} onSave={(updates) => editVendorProfile(myVendorProfile.id, updates)} />
      )}

      {/* Gamified Loyalty Banner */}
      <div className="bg-gradient-to-r from-amber-500 via-orange-500 to-amber-600 rounded-2xl text-white p-6 shadow-xl relative overflow-hidden">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 relative z-10">
          <div className="space-y-2">
            <div className="flex items-center gap-2 text-amber-100 text-xs font-extrabold uppercase tracking-wider">
              <Coins className="w-4 h-4 text-amber-200" /> Vendor Gamified Loyalty Hub
            </div>
            <h2 className="text-3xl font-black flex items-center gap-2 tracking-tight">
              🪙 {myVendorProfile?.loyalty_coins || 0} Loyalty Coins
            </h2>
            <p className="text-sm text-amber-100 max-w-xl leading-relaxed">
              Every time you complete a sale and deliver goods to a customer, you get <strong>100 Loyalty Coins</strong> instantly. Use your coins to feature products across SulejaMarket!
            </p>
          </div>

          <div className="bg-white/15 backdrop-blur-md rounded-xl p-4 border border-white/20 shrink-0 text-center space-y-1">
            <div className="text-xs text-amber-100 font-medium">Product Feature Cost</div>
            <div className="text-2xl font-black text-white">100 Coins / Item</div>
            <div className="text-[11px] text-amber-100 font-semibold">
              {(myVendorProfile?.loyalty_coins || 0) >= 100 ? "✨ You can feature an item now!" : `Need ${100 - (myVendorProfile?.loyalty_coins || 0)} more coins to feature`}
            </div>
          </div>
        </div>

        {/* Loyalty Activity Log */}
        {loyaltyTransactions.length > 0 && (
          <div className="mt-5 pt-4 border-t border-white/20 text-xs">
            <div className="font-bold text-amber-100 mb-2 flex items-center gap-1.5">
              <History className="w-3.5 h-3.5" /> Recent Coin Activity Log
            </div>
            <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-2">
              {loyaltyTransactions.slice(0, 6).map((t) => (
                <div key={t.id} className="bg-black/20 px-3 py-2 rounded-lg border border-white/10 flex justify-between items-center">
                  <span className="text-amber-50 line-clamp-1">{t.description}</span>
                  <span className={`font-bold shrink-0 ml-2 font-mono ${t.amount > 0 ? "text-emerald-300" : "text-amber-200"}`}>
                    {t.amount > 0 ? `+${t.amount}` : t.amount}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      <div className="flex flex-col lg:grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-1 bg-white rounded-lg border p-5">
          <div className="flex justify-between items-center mb-4">
            <h2 className="font-bold flex items-center gap-2">
              <Plus className="w-4 h-4" /> {editingId ? "Edit product" : "New product"}
            </h2>
            {editingId && (
              <Button size="sm" variant="outline" onClick={() => { setEditingId(null); setForm({ name: "", price: "", old: "", category: "", summary: "", description: "", img1: "", img2: "", img3: "", colors: "", sizes: "", is_top: false }); }}>
                Cancel
              </Button>
            )}
          </div>
          <form onSubmit={submit} className="space-y-3">
            <div><label className="text-xs font-medium">Product name *</label><Input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Wireless Headphones" /></div>
            <div className="grid grid-cols-2 gap-2">
              <div><label className="text-xs font-medium">Price ₦ *</label><Input required type="number" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="25000" /></div>
              <div><label className="text-xs font-medium">Old price</label><Input type="number" value={form.old} onChange={(e) => setForm({ ...form, old: e.target.value })} placeholder="35000" /></div>
            </div>
            <div>
              <label className="text-xs font-medium">Category</label>
              <Select value={form.category} onValueChange={(v) => setForm({ ...form, category: v })}>
                <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                <SelectContent>
                  {CATEGORIES.filter(c => c !== "Official Store").map((c) => (
                    <SelectItem key={c} value={c}>{c}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            
            {form.category === "Fashion" && (
              <div className="grid grid-cols-2 gap-2 bg-orange-50/50 p-2 rounded border border-orange-100">
                <div><label className="text-xs font-medium">Colors (comma separated)</label><Input value={form.colors} onChange={(e) => setForm({ ...form, colors: e.target.value })} placeholder="Red, Blue, Black" /></div>
                <div><label className="text-xs font-medium">Sizes (comma separated)</label><Input value={form.sizes} onChange={(e) => setForm({ ...form, sizes: e.target.value })} placeholder="S, M, L, XL" /></div>
              </div>
            )}

            <div><label className="text-xs font-medium">Short summary</label><Input value={form.summary} onChange={(e) => setForm({ ...form, summary: e.target.value })} placeholder="Brief highlight" /></div>
            <div><label className="text-xs font-medium">Description</label><Textarea rows={3} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Full product details" /></div>
            
            <div className="space-y-2">
              <label className="text-xs font-medium">Product Images</label>
              <div className="grid gap-2">
                <ImageUpload value={form.img1} onChange={(url) => setForm({ ...form, img1: url })} />
                <ImageUpload value={form.img2} onChange={(url) => setForm({ ...form, img2: url })} />
                <ImageUpload value={form.img3} onChange={(url) => setForm({ ...form, img3: url })} />
              </div>
            </div>

            {myVendorProfile?.is_verified && (
              <div className="flex items-center space-x-2 pt-2 border-t">
                <input type="checkbox" id="is_top" checked={form.is_top} onChange={(e) => setForm({ ...form, is_top: e.target.checked })} className="accent-orange-500 w-4 h-4" />
                <label htmlFor="is_top" className="text-sm font-medium">Feature in Top Sellers section</label>
              </div>
            )}

            <Button type="submit" className="w-full bg-orange-500 hover:bg-orange-600 mt-4">
              <CheckCircle2 className="w-4 h-4 mr-1" /> {editingId ? "Update listing" : "Publish listing"}
            </Button>
          </form>
        </div>

        <div className="lg:col-span-2 bg-white rounded-lg border">
          <div className="px-5 py-3 border-b font-bold flex items-center justify-between">
            <span className="flex items-center gap-2"><Package className="w-4 h-4" /> Your listings</span>
            <span className="text-xs text-neutral-500 font-normal">Use 100 Loyalty Coins to feature products</span>
          </div>
          {mine.length === 0 ? (
            <div className="p-10 text-center text-sm text-neutral-500">No products yet. Create your first listing on the left.</div>
          ) : (
            <div className="divide-y">
              {mine.map((p) => (
                <div key={p.id} className="flex flex-wrap items-center gap-4 p-4 hover:bg-neutral-50/80 transition">
                  <img src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/80/80`)} alt={p.name} className="w-14 h-14 rounded object-cover border" />
                  <div className="flex-1 min-w-[150px]">
                    <div className="text-sm font-medium line-clamp-1 flex items-center gap-2">
                      {p.name}
                      {p.is_featured && (
                        <span className="text-[10px] font-bold text-amber-800 bg-amber-100 border border-amber-300 px-2 py-0.5 rounded-full flex items-center gap-1">
                          <Sparkles className="w-3 h-3 text-amber-600 fill-amber-500" /> Featured
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-neutral-500">{p.category}</div>
                  </div>
                  <div className="text-sm font-bold">₦ {fmt(p.price)}</div>

                  {/* Feature with Loyalty Coins Button */}
                  {!p.is_featured ? (
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleFeature(p)}
                      className="text-xs bg-amber-50 text-amber-900 border-amber-200 hover:bg-amber-100 hover:border-amber-300 font-bold"
                    >
                      <Sparkles className="w-3.5 h-3.5 mr-1 text-amber-600 fill-amber-400" /> Feature (100 Coins)
                    </Button>
                  ) : (
                    <span className="text-xs font-bold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
                      ✨ Active Featured
                    </span>
                  )}

                  <div className="flex items-center gap-2">
                    <button onClick={() => handleEdit(p)} className="text-neutral-400 hover:text-blue-500 p-1" title="Edit">
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-4 h-4"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                    </button>
                    <button onClick={() => { if(confirm("Are you sure?")) removeProduct(p.id); }} className="text-neutral-400 hover:text-red-500 p-1" title="Delete">
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        {/* Wallet Section */}
        <div className="bg-white rounded-lg border p-5">
          <div className="flex items-center gap-2 font-bold mb-4 border-b pb-2"><Wallet className="w-5 h-5 text-orange-500" /> Wallet & Payouts</div>
          <div className="bg-orange-50 rounded-lg p-5 border border-orange-100 flex items-center justify-between mb-5">
            <div>
              <div className="text-sm text-orange-800 font-medium mb-1">Available Balance</div>
              <div className="text-3xl font-bold text-orange-600">₦ {fmt(myVendorProfile?.wallet_balance || 0)}</div>
            </div>
            <Button 
              onClick={async () => {
                const amountStr = prompt("Enter amount to withdraw (A 1% VAT fee will be deducted from this amount):");
                if (!amountStr) return;
                const amount = Number(amountStr);
                if (isNaN(amount) || amount <= 0) return toast.error("Invalid amount");
                if (amount > (myVendorProfile?.wallet_balance || 0)) return toast.error("Insufficient balance");
                
                const res = await requestWithdrawal(user!.email, amount);
                if (res.success) toast.success("Withdrawal requested");
                else toast.error(res.error || "Failed to request withdrawal");
              }}
              className="bg-orange-500 hover:bg-orange-600 shadow"
            >
              Withdraw Funds
            </Button>
          </div>

          <h3 className="font-bold text-sm mb-3">Withdrawal History</h3>
          {withdrawals.length === 0 ? (
            <div className="text-sm text-neutral-500 py-4 text-center">No withdrawal history.</div>
          ) : (
            <div className="space-y-3">
              {withdrawals.map(w => (
                <div key={w.id} className="flex items-center justify-between border-b pb-2 last:border-0">
                  <div>
                    <div className="text-sm font-medium">₦ {fmt(w.amount * 0.99)} <span className="text-xs text-neutral-400 font-normal">(after 1% VAT)</span></div>
                    <div className="text-xs text-neutral-500">{new Date(w.requestedAt * 1000).toLocaleString()}</div>
                  </div>
                  <div>
                    <span className={`text-xs px-2 py-1 rounded-full ${
                      w.status === 'approved' ? 'bg-emerald-100 text-emerald-800' :
                      w.status === 'rejected' ? 'bg-red-100 text-red-800' :
                      'bg-amber-100 text-amber-800'
                    }`}>
                      {w.status.charAt(0).toUpperCase() + w.status.slice(1)}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Orders Section */}
        <div className="bg-white rounded-lg border p-5">
          <div className="flex items-center justify-between border-b pb-2 mb-4">
            <div className="flex items-center gap-2 font-bold">
              <Truck className="w-5 h-5 text-orange-500" /> Vendor Delivery Fulfillment
            </div>
            <span className="text-[11px] font-semibold bg-orange-50 text-orange-600 border border-orange-200 px-2 py-0.5 rounded-full">
              Manual Dispatch Control
            </span>
          </div>

          {myOrders.length === 0 ? (
            <div className="text-sm text-neutral-500 py-8 text-center">No orders to fulfill yet.</div>
          ) : (
            <div className="space-y-5">
              {myOrders.map(o => {
                const isDelivered = o.status === 'delivered';
                
                const milestoneSteps: { key: OrderStatus; label: string; actionLabel: string; adminOnly?: boolean }[] = [
                  { key: 'placed', label: '1. Confirmed', actionLabel: 'Order Received' },
                  { key: 'processing', label: '2. Packed', actionLabel: 'Mark Packed' },
                  { key: 'shipped', label: '3. Dispatched', actionLabel: 'Mark Shipped' },
                  { key: 'out_for_delivery', label: '4. Out for Delivery', actionLabel: 'Out for Delivery' },
                  { key: 'delivered', label: '5. Delivered 🔒', actionLabel: 'Mark Delivered', adminOnly: true },
                ];

                const currentIdx = milestoneSteps.findIndex(s => s.key === o.status);
                const nextStepCandidate = milestoneSteps[currentIdx + 1];
                // Vendor can only advance up to out_for_delivery. Delivered is Admin-only.
                const nextStep = (nextStepCandidate && !nextStepCandidate.adminOnly) ? nextStepCandidate : null;

                const handleStatusChange = (newStatus: OrderStatus) => {
                  if (newStatus === 'delivered') {
                    toast.error("Only SulejaMarket Admin can mark an order as Delivered to confirm customer receipt and release funds.");
                    return;
                  }
                  setOrderStatus(o.id, newStatus);
                  const formatted = newStatus.replace(/_/g, ' ').toUpperCase();
                  toast.success(`Order ${o.id} delivery milestone set to ${formatted}`);
                };

                return (
                  <div key={o.id} className="border rounded-xl p-4 bg-neutral-50/50 space-y-3 hover:border-neutral-300 transition">
                    {/* Header info */}
                    <div className="flex flex-wrap justify-between items-start gap-2">
                      <div>
                        <div className="font-bold text-sm text-neutral-900 flex items-center gap-2">
                          Order {o.id}
                          <Link to="/orders/$id" params={{ id: o.id }} target="_blank" className="text-xs text-orange-500 font-normal hover:underline">
                            (View Live Map)
                          </Link>
                        </div>
                        <div className="text-xs text-neutral-500">{new Date(o.createdAt).toLocaleString()}</div>
                      </div>
                      <span className={`text-xs font-bold uppercase px-2.5 py-1 rounded-full border ${
                        isDelivered ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-orange-50 text-orange-700 border-orange-200'
                      }`}>
                        {o.status.replace(/_/g, ' ')}
                      </span>
                    </div>
                    
                    {/* Items */}
                    <div className="bg-white p-3 rounded-lg border text-xs space-y-1.5">
                      <div className="font-semibold text-neutral-700 mb-1 text-[11px] uppercase tracking-wider">Ordered Items</div>
                      {o.items.filter(item => vendorProducts.some(p => p.id === item.id && p.vendorEmail === user?.email)).map(item => (
                        <div key={item.id} className="flex justify-between items-center">
                          <span className="text-neutral-800 font-medium">{item.qty}x {item.name}</span>
                          <span className="font-bold text-neutral-900">₦ {fmt(item.qty * item.price)}</span>
                        </div>
                      ))}
                    </div>

                    {/* Delivery Address */}
                    <div className="text-xs text-neutral-600 bg-white p-2.5 rounded-lg border flex flex-col gap-0.5">
                      <span className="font-semibold text-neutral-900">Delivery Address:</span>
                      <span>{o.address.name} ({o.address.phone})</span>
                      <span className="text-neutral-500">{o.address.street}, {o.address.city}, {o.address.state}</span>
                    </div>

                    {/* Driver Phone Assignment */}
                    <VendorDriverPhoneForm 
                      orderId={o.id} 
                      currentPhone={o.driverPhone} 
                      onSave={updateOrderDriverPhone} 
                    />

                    {/* Vendor Manual Controls */}
                    <div className="space-y-2 pt-1 border-t">
                      <div className="text-xs font-bold text-neutral-700 flex justify-between items-center">
                        <span>Delivery Process Control:</span>
                        {nextStep && !isDelivered && (
                          <Button 
                            size="sm" 
                            onClick={() => handleStatusChange(nextStep.key)}
                            className="h-7 text-xs bg-orange-500 hover:bg-orange-600 text-white font-semibold"
                          >
                            Advance to {nextStep.actionLabel} →
                          </Button>
                        )}
                      </div>

                      {/* Milestone Selector Buttons */}
                      <div className="grid grid-cols-2 sm:grid-cols-5 gap-1.5">
                        {milestoneSteps.map((step, idx) => {
                          const isActive = o.status === step.key;
                          const isDone = currentIdx >= idx;
                          const isAdminOnly = step.adminOnly;
                          
                          return (
                            <button
                              key={step.key}
                              type="button"
                              onClick={() => {
                                if (isAdminOnly) {
                                  toast.error("Only SulejaMarket Admin can mark an order as Delivered to confirm customer receipt and release funds.");
                                  return;
                                }
                                handleStatusChange(step.key);
                              }}
                              className={`text-[11px] py-1.5 px-2 rounded font-medium border text-center transition ${
                                isActive 
                                  ? 'bg-orange-500 text-white border-orange-500 font-bold shadow-sm' 
                                  : isDone 
                                  ? 'bg-orange-50 text-orange-700 border-orange-200 hover:bg-orange-100' 
                                  : isAdminOnly
                                  ? 'bg-neutral-100 text-neutral-400 border-neutral-200 cursor-not-allowed'
                                  : 'bg-white text-neutral-600 border-neutral-200 hover:border-orange-300'
                              }`}
                              title={isAdminOnly ? "Admin Confirmation Required for Payout Release" : undefined}
                            >
                              {step.label}
                            </button>
                          );
                        })}
                      </div>

                      {o.status === 'out_for_delivery' && (
                        <div className="text-xs text-amber-800 font-semibold bg-amber-50 border border-amber-200 p-2.5 rounded-lg text-center">
                          Package is Out for Delivery. Awaiting Admin confirmation to finalize delivery and release wallet payment.
                        </div>
                      )}

                      {isDelivered && (
                        <div className="text-xs text-emerald-700 font-bold bg-emerald-50 border border-emerald-200 p-2 rounded-lg text-center flex items-center justify-center gap-1.5">
                          <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                          Order Delivered — Confirmed by Admin & Payment Released to Wallet
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <Link to="/" className="text-sm text-orange-500 hover:underline">← Back to storefront</Link>
    </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>
  );
}

function StoreCustomization({ profile, onSave }: { profile: any, onSave: (u: any) => void }) {
  const [banner, setBanner] = useState(profile.banner || "");
  const [logo, setLogo] = useState(profile.logo || "");
  
  const handleSave = () => {
    onSave({ banner, logo });
    toast.success("Store profile updated");
  };

  return (
    <div className="bg-white rounded-lg border p-5">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between mb-4 gap-2">
        <h2 className="font-bold flex items-center gap-2">
          <Store className="w-4 h-4" /> Store Customization
        </h2>
        <Button size="sm" onClick={handleSave} className="bg-neutral-900 hover:bg-neutral-800 text-white shrink-0">Save Changes</Button>
      </div>
      <div className="grid md:grid-cols-2 gap-6">
        <div>
          <label className="text-xs font-medium block mb-2">Store Banner (e.g. 1200x300)</label>
          <ImageUpload value={banner} onChange={setBanner} />
          <p className="text-[10px] text-neutral-500 mt-1">Appears at the top of your store page.</p>
        </div>
        <div>
          <label className="text-xs font-medium block mb-2">Store Logo / Icon</label>
          <div className="w-32 h-32">
            <ImageUpload value={logo} onChange={setLogo} />
          </div>
          <p className="text-[10px] text-neutral-500 mt-1">Your brand identity.</p>
        </div>
      </div>
    </div>
  );
}
