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 { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { ImageUpload } from "@/components/ui/image-upload";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Package, ChevronRight, RotateCcw, CheckCircle2, Store, Settings, Eye, Edit, Trash2, LayoutDashboard, ExternalLink, Plus, Tag, Video, Star, XCircle } from "lucide-react";
import { toast } from "sonner";
import { useStore, fmt, statusLabel, type OrderStatus, type VendorProfile, type Product } from "@/lib/store";

export const Route = createFileRoute("/admin")({
  head: () => ({
    meta: [
      { title: "Admin — Dashboard • SulejaMarket" },
      { name: "description", content: "Manage orders and vendors." },
    ],
  }),
  component: AdminPage,
});

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

function EditVendorForm({ vendor, onClose, onSave }: { vendor: VendorProfile, onClose: () => void, onSave: (id: string, updates: Partial<VendorProfile>) => void }) {
  const [form, setForm] = useState(vendor);
  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave(vendor.id, form);
    onClose();
  };
  return (
    <form onSubmit={submit} className="space-y-4 pt-2">
      <div className="grid grid-cols-2 gap-3">
        <div><label className="text-xs font-medium">Business Name</label><Input value={form.businessName} onChange={(e) => setForm({...form, businessName: e.target.value})} /></div>
        <div><label className="text-xs font-medium">Contact Name</label><Input value={form.contactName} onChange={(e) => setForm({...form, contactName: e.target.value})} /></div>
        <div><label className="text-xs font-medium">Email</label><Input value={form.contactEmail} onChange={(e) => setForm({...form, contactEmail: e.target.value})} /></div>
        <div><label className="text-xs font-medium">Phone</label><Input value={form.contactPhone} onChange={(e) => setForm({...form, contactPhone: e.target.value})} /></div>
      </div>
      <div><label className="text-xs font-medium">Address</label><Input value={form.address} onChange={(e) => setForm({...form, address: e.target.value})} /></div>
      <DialogFooter>
        <Button variant="outline" type="button" onClick={onClose}>Cancel</Button>
        <Button type="submit" className="bg-orange-500 hover:bg-orange-600">Save Changes</Button>
      </DialogFooter>
    </form>
  );
}

function EditProductForm({ product, onClose, onSave }: { product: Product, onClose: () => void, onSave: (id: string, updates: Partial<Product>) => void }) {
  const [form, setForm] = useState({
    ...product,
    img: product.images?.[0] || "",
    is_flash: !!product.is_flash,
    is_top: !!product.is_top,
    description: product.description || ""
  });
  
  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    const { img, ...rest } = form;
    const images = img ? [img] : undefined;
    onSave(product.id, {
      ...rest,
      price: Number(form.price),
      old: form.old ? Number(form.old) : undefined,
      images: images || product.images,
    });
    onClose();
  };
  return (
    <form onSubmit={submit} className="space-y-4 pt-2">
      <div className="grid grid-cols-2 gap-3">
        <div className="col-span-2">
          <label className="text-xs font-medium">Primary Image</label>
          <ImageUpload value={form.img} onChange={(url) => setForm({...form, img: url})} />
        </div>
        <div><label className="text-xs font-medium">Name</label><Input value={form.name} onChange={(e) => setForm({...form, name: e.target.value})} /></div>
        <div><label className="text-xs font-medium">Category</label><Input value={form.category} onChange={(e) => setForm({...form, category: e.target.value})} /></div>
        <div><label className="text-xs font-medium">Price ₦</label><Input type="number" value={form.price} onChange={(e) => setForm({...form, price: Number(e.target.value)})} /></div>
        <div><label className="text-xs font-medium">Old Price</label><Input type="number" value={form.old || ""} onChange={(e) => setForm({...form, old: Number(e.target.value)})} /></div>
        <div className="col-span-2">
          <label className="text-xs font-medium">Description</label>
          <Textarea className="h-20" value={form.description} onChange={(e) => setForm({...form, description: e.target.value})} />
        </div>
        <div className="col-span-2 flex gap-6 mt-2">
          <div className="flex items-center space-x-2">
            <Checkbox id="is_flash" checked={form.is_flash} onCheckedChange={(c) => setForm({...form, is_flash: !!c})} />
            <label htmlFor="is_flash" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Flash Sale</label>
          </div>
          <div className="flex items-center space-x-2">
            <Checkbox id="is_top" checked={form.is_top} onCheckedChange={(c) => setForm({...form, is_top: !!c})} />
            <label htmlFor="is_top" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Top Seller</label>
          </div>
        </div>
      </div>
      <DialogFooter>
        <Button variant="outline" type="button" onClick={onClose}>Cancel</Button>
        <Button type="submit" className="bg-orange-500 hover:bg-orange-600">Save Changes</Button>
      </DialogFooter>
    </form>
  );
}

function AdminPage() {
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [tab, setTab] = useState<"orders" | "vendors" | "products" | "withdrawals" | "reviews" | "settings">("orders");
  const [viewVendor, setViewVendor] = useState<VendorProfile | null>(null);
  const [editVendor, setEditVendor] = useState<VendorProfile | null>(null);
  const [editProduct, setEditProduct] = useState<Product | null>(null);
  const [adminReviews, setAdminReviews] = useState<any[]>([]);

  const { orders, setOrderStatus, updateOrderDriverPhone, advanceOrder, hydrated, vendors, adminApproveVendor, adminEditVendor, adminDeleteVendor, paystackKey, setPaystackKey, topBanners, setTopBanners, heroBanners, setHeroBanners, getAllProducts, editProduct: storeEditProduct, removeProduct, withdrawals, fetchWithdrawals, adminUpdateWithdrawal } = useStore();

  const fetchAdminReviews = () => {
    fetch("/api/reviews.php?action=admin_list")
      .then((r) => r.json())
      .then((data) => {
        if (Array.isArray(data)) setAdminReviews(data);
      })
      .catch(() => {});
  };

  useEffect(() => {
    if (tab === "withdrawals") fetchWithdrawals();
    if (tab === "reviews") fetchAdminReviews();
  }, [tab, fetchWithdrawals]);

  const handleApproveReview = async (id: string) => {
    try {
      const res = await fetch("/api/reviews.php?action=approve", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      const data = await res.json();
      if (data.success) {
        setAdminReviews((prev) => prev.map((r) => (r.id === id ? { ...r, status: "approved" } : r)));
        toast.success("Video review approved! It is now visible on the product page.");
      }
    } catch {
      toast.error("Failed to approve review.");
    }
  };

  const handleRejectReview = async (id: string) => {
    try {
      const res = await fetch("/api/reviews.php?action=reject", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      const data = await res.json();
      if (data.success) {
        setAdminReviews((prev) => prev.map((r) => (r.id === id ? { ...r, status: "rejected" } : r)));
        toast.info("Video review rejected.");
      }
    } catch {
      toast.error("Failed to reject review.");
    }
  };

  const handleDeleteReview = async (id: string) => {
    if (!confirm("Are you sure you want to permanently delete this video review?")) return;
    try {
      const res = await fetch("/api/reviews.php?action=delete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      const data = await res.json();
      if (data.success) {
        setAdminReviews((prev) => prev.filter((r) => r.id !== id));
        toast.success("Video review deleted permanently.");
      }
    } catch {
      toast.error("Failed to delete review.");
    }
  };

  const setStatus = (id: string, target: OrderStatus) => {
    const order = orders.find((o) => o.id === id);
    if (!order) return;
    const from = steps.indexOf(order.status);
    const to = steps.indexOf(target);
    if (to <= from) return;
    setOrderStatus(id, target);
  };

  const pendingReviewsCount = adminReviews.filter(r => (r.status || 'pending') === 'pending').length;

  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)} />

      <Dialog open={!!editProduct} onOpenChange={(o) => !o && setEditProduct(null)}>
        <DialogContent>
          <DialogHeader><DialogTitle>Edit Product</DialogTitle></DialogHeader>
          {editProduct && <EditProductForm product={editProduct} onClose={() => setEditProduct(null)} onSave={storeEditProduct} />}
        </DialogContent>
      </Dialog>

      <main className="max-w-[1100px] mx-auto px-4 py-8">
        <div className="mb-6 flex flex-col sm:flex-row sm:items-end justify-between gap-4">
          <div>
            <div className="text-xs text-neutral-500">Admin</div>
            <h1 className="text-2xl font-bold">Dashboard</h1>
          </div>
          <div className="flex bg-white rounded-lg border p-1 self-start sm:self-auto flex-wrap gap-1">
            <button onClick={() => setTab("orders")} className={`px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition ${tab === "orders" ? "bg-orange-50 text-orange-600" : "text-neutral-600 hover:bg-neutral-100"}`}>Orders</button>
            <button onClick={() => setTab("vendors")} className={`px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition ${tab === "vendors" ? "bg-orange-50 text-orange-600" : "text-neutral-600 hover:bg-neutral-100"}`}>Vendors</button>
            <button onClick={() => setTab("products")} className={`px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition ${tab === "products" ? "bg-orange-50 text-orange-600" : "text-neutral-600 hover:bg-neutral-100"}`}>Products</button>
            <button onClick={() => setTab("reviews")} className={`px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition relative ${tab === "reviews" ? "bg-orange-50 text-orange-600" : "text-neutral-600 hover:bg-neutral-100"}`}>
              Reviews
              {pendingReviewsCount > 0 && (
                <span className="ml-1 px-1.5 py-0.2 bg-amber-500 text-white text-[10px] font-bold rounded-full">
                  {pendingReviewsCount}
                </span>
              )}
            </button>
            <button onClick={() => setTab("withdrawals")} className={`px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition ${tab === "withdrawals" ? "bg-orange-50 text-orange-600" : "text-neutral-600 hover:bg-neutral-100"}`}>Withdrawals</button>
            <button onClick={() => setTab("settings")} className={`px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition ${tab === "settings" ? "bg-orange-50 text-orange-600" : "text-neutral-600 hover:bg-neutral-100"}`}>Settings</button>
          </div>
        </div>

        {!hydrated ? (
          <div className="text-center py-16 text-sm text-neutral-500">Loading…</div>
        ) : tab === "orders" ? (
          orders.length === 0 ? (
            <div className="bg-white rounded-lg border p-10 text-center">
              <Package className="w-12 h-12 text-neutral-300 mx-auto mb-3" />
              <h2 className="text-lg font-bold">No orders yet</h2>
            </div>
          ) : (
            <div className="space-y-4">
              {orders.map((o) => {
                const idx = steps.indexOf(o.status);
                const next = steps[idx + 1];
                return (
                  <div key={o.id} className="bg-white rounded-lg border p-5">
                    <div className="flex flex-wrap items-start justify-between gap-4 mb-4">
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-bold">{o.id}</span>
                          <span className="text-xs px-2 py-0.5 rounded-full bg-orange-100 text-orange-700 font-medium">
                            {statusLabel[o.status]}
                          </span>
                        </div>
                        <div className="text-xs text-neutral-500 mt-1">
                          {new Date(o.createdAt).toLocaleString()} · {o.items.length} item{o.items.length !== 1 ? "s" : ""} · ₦ {fmt(o.total)}
                        </div>
                        <div className="text-xs text-neutral-500 flex flex-wrap items-center gap-2 mt-1">
                          <span>{o.address.name} — {o.address.city}, {o.address.state}</span>
                          <span className="text-neutral-300">•</span>
                          {o.driverPhone ? (
                            <span className="text-emerald-700 font-mono font-bold bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">
                              Driver: {o.driverPhone}
                            </span>
                          ) : (
                            <span className="text-amber-700 bg-amber-50 px-2 py-0.5 rounded border border-amber-200 text-[11px]">
                              Driver: Not assigned
                            </span>
                          )}
                          <form
                            onSubmit={(e) => {
                              e.preventDefault();
                              const input = (e.currentTarget.elements.namedItem("phone") as HTMLInputElement).value.trim();
                              if (!/^\d{11}$/.test(input)) {
                                toast.error("Driver phone number must be an 11-digit number (e.g. 08031234567)");
                                return;
                              }
                              updateOrderDriverPhone(o.id, input);
                              toast.success(`Driver phone number (${input}) updated for Order ${o.id}!`);
                            }}
                            className="inline-flex items-center gap-1 ml-1"
                          >
                            <Input
                              name="phone"
                              defaultValue={o.driverPhone || ""}
                              placeholder="Update 11 digits"
                              maxLength={11}
                              className="h-6 text-[11px] w-32 font-mono bg-neutral-50 px-1.5"
                            />
                            <Button type="submit" size="sm" variant="outline" className="h-6 text-[10px] px-2">
                              Save
                            </Button>
                          </form>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Link to="/admin/$id" params={{ id: o.id }}>
                          <Button variant="outline" size="sm">View details</Button>
                        </Link>
                        <Link to="/orders/$id" params={{ id: o.id }}>
                          <Button variant="outline" size="sm">Tracking</Button>
                        </Link>
                        {next ? (
                          <Button 
                            size="sm" 
                            className={next === 'delivered' ? "bg-emerald-600 hover:bg-emerald-700 text-white font-bold" : "bg-orange-500 hover:bg-orange-600"} 
                            onClick={() => {
                              setOrderStatus(o.id, next);
                              if (next === 'delivered') {
                                toast.success(`Order ${o.id} marked as DELIVERED! Payment released to vendor wallet.`);
                              }
                            }}
                          >
                            {next === 'delivered' ? "Confirm Delivery & Release Payout" : `Advance to ${statusLabel[next]}`} <ChevronRight className="w-4 h-4 ml-1" />
                          </Button>
                        ) : (
                          <Button size="sm" variant="outline" disabled><RotateCcw className="w-3 h-3 mr-1" /> Delivered & Paid</Button>
                        )}
                      </div>
                    </div>
                    <div className="flex flex-wrap gap-2 items-center">
                      <span className="text-xs font-semibold text-neutral-500 mr-1">Admin Controls:</span>
                      {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(o.id, s);
                              if (s === 'delivered') {
                                toast.success(`Order ${o.id} marked as DELIVERED! Payment released to vendor wallet.`);
                              }
                            }}
                            className={[
                              "text-xs px-3 py-1.5 rounded-full border 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>
                  </div>
                );
              })}
            </div>
          )
        ) : tab === "vendors" ? (
          vendors.length === 0 ? (
            <div className="bg-white rounded-lg border p-10 text-center">
              <Store className="w-12 h-12 text-neutral-300 mx-auto mb-3" />
              <h2 className="text-lg font-bold">No vendors yet</h2>
              <p className="text-sm text-neutral-500 mt-1">Vendor applications will appear here.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {vendors.map((v) => (
                <div key={v.id} className="bg-white rounded-lg border p-5 flex flex-wrap items-center justify-between gap-4">
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-lg">{v.businessName}</span>
                      {v.status === "approved" ? (
                        <span className="text-xs px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 font-medium">Approved</span>
                      ) : (
                        <span className="text-xs px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 font-medium">Pending</span>
                      )}
                    </div>
                    <div className="text-sm text-neutral-500 mt-1">{v.contactName} · {v.contactEmail}</div>
                    <div className="text-xs text-neutral-400 mt-0.5">Applied {new Date(v.appliedAt).toLocaleDateString()}</div>
                  </div>
                  <div className="flex gap-2 items-center flex-wrap mt-2 sm:mt-0">
                    {v.status === "pending" && (
                      <Button size="sm" onClick={() => adminApproveVendor(v.id)} className="bg-emerald-500 hover:bg-emerald-600">
                        <CheckCircle2 className="w-4 h-4 mr-1.5" /> Approve
                      </Button>
                    )}
                    <Button size="sm" variant="outline" onClick={() => setViewVendor(v)}><Eye className="w-4 h-4 mr-1" /> View Details</Button>
                    <Button size="sm" variant="outline" onClick={() => setEditVendor(v)}><Edit className="w-4 h-4 mr-1" /> Edit</Button>
                    <Button size="sm" variant="outline" className="text-red-500 hover:text-red-600 hover:bg-red-50" onClick={() => { if(confirm("Are you sure you want to delete this vendor?")) adminDeleteVendor(v.id) }}><Trash2 className="w-4 h-4 mr-1" /> Delete</Button>
                    {v.status === "approved" && (
                      <>
                        <Link to="/admin/vendors/$id" params={{ id: v.id }}>
                          <Button size="sm" variant="outline"><LayoutDashboard className="w-4 h-4 mr-1" /> Dashboard</Button>
                        </Link>
                        {v.storeSlug && (
                          <Link to="/$storeSlug" params={{ storeSlug: v.storeSlug }} target="_blank">
                            <Button size="sm" variant="outline" className="text-orange-600 hover:text-orange-700 hover:bg-orange-50"><ExternalLink className="w-4 h-4 mr-1" /> Storefront</Button>
                          </Link>
                        )}
                      </>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )
        ) : tab === "products" ? (
          <div className="space-y-4">
            {getAllProducts().map((p) => (
              <div key={p.id} className="bg-white rounded-lg border p-4 flex flex-wrap items-center justify-between gap-4">
                <div className="flex items-center gap-3">
                  <img src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/60/60`)} className="w-12 h-12 rounded object-cover border" />
                  <div>
                    <div className="font-medium text-sm">{p.name}</div>
                    <div className="text-xs text-neutral-500">{p.category} {p.vendorEmail ? `· By Vendor` : `· Official`}</div>
                  </div>
                </div>
                <div className="flex items-center gap-4">
                  <div className="font-bold text-sm">₦ {fmt(p.price)}</div>
                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => setEditProduct(p)}><Edit className="w-4 h-4 mr-1" /> Edit</Button>
                    <Button size="sm" variant="outline" className="text-red-500 hover:text-red-600 hover:bg-red-50" onClick={() => { if(confirm("Are you sure?")) removeProduct(p.id); }}><Trash2 className="w-4 h-4 mr-1" /> Delete</Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : tab === "withdrawals" ? (
          withdrawals.length === 0 ? (
            <div className="bg-white rounded-lg border p-10 text-center">
              <h2 className="text-lg font-bold">No withdrawals</h2>
              <p className="text-sm text-neutral-500 mt-1">There are no withdrawal requests.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {withdrawals.map(w => (
                <div key={w.id} className="bg-white rounded-lg border p-5 flex flex-wrap items-center justify-between gap-4">
                  <div>
                    <div className="font-bold text-lg">Payable: ₦ {fmt(w.amount * 0.99)} <span className="text-xs font-normal text-neutral-400">(1% VAT deducted from ₦ {fmt(w.amount)})</span></div>
                    <div className="text-sm text-neutral-500 mt-1">Vendor: {w.vendorEmail}</div>
                    <div className="text-xs text-neutral-400 mt-0.5">Requested: {new Date(w.requestedAt * 1000).toLocaleString()}</div>
                  </div>
                  <div className="flex items-center gap-2">
                    {w.status === "pending" ? (
                      <>
                        <Button size="sm" onClick={() => adminUpdateWithdrawal(w.id, "approve")} className="bg-emerald-500 hover:bg-emerald-600">
                          <CheckCircle2 className="w-4 h-4 mr-1.5" /> Approve
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => adminUpdateWithdrawal(w.id, "reject")} className="text-red-500 hover:bg-red-50 hover:text-red-600">
                          Reject
                        </Button>
                      </>
                    ) : (
                      <span className={`text-xs px-2 py-1 rounded-full ${
                        w.status === 'approved' ? 'bg-emerald-100 text-emerald-800' :
                        'bg-red-100 text-red-800'
                      }`}>
                        {w.status.charAt(0).toUpperCase() + w.status.slice(1)}
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )
        ) : tab === "reviews" ? (
          adminReviews.length === 0 ? (
            <div className="bg-white rounded-lg border p-10 text-center">
              <Video className="w-12 h-12 text-neutral-300 mx-auto mb-3" />
              <h2 className="text-lg font-bold">No customer video reviews</h2>
              <p className="text-sm text-neutral-500 mt-1">Submitted video reviews requiring admin approval will appear here.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {adminReviews.map((r) => (
                <div key={r.id} className="bg-white rounded-lg border p-5 flex flex-col md:flex-row gap-5">
                  {r.video_url && (
                    <div className="w-full md:w-56 h-40 bg-black rounded-lg overflow-hidden shrink-0 border relative">
                      <video src={r.video_url} controls className="w-full h-full object-cover" />
                    </div>
                  )}
                  <div className="flex-1 flex flex-col justify-between">
                    <div>
                      <div className="flex flex-wrap items-center justify-between gap-2 mb-2">
                        <div className="flex items-center gap-2">
                          <span className="font-bold text-base">{r.title || "Customer Review"}</span>
                          <span className={`text-xs px-2.5 py-0.5 rounded-full font-bold uppercase ${
                            r.status === 'approved' ? 'bg-emerald-100 text-emerald-800 border border-emerald-300' :
                            r.status === 'rejected' ? 'bg-red-100 text-red-800 border border-red-300' :
                            'bg-amber-100 text-amber-800 border border-amber-300'
                          }`}>
                            {r.status || 'pending'}
                          </span>
                        </div>
                        <div className="flex items-center text-amber-500 font-bold text-sm">
                          {Array.from({ length: 5 }).map((_, i) => (
                            <Star key={i} className={`w-4 h-4 ${i < (r.rating || 5) ? 'fill-amber-400 text-amber-400' : 'text-neutral-300'}`} />
                          ))}
                          <span className="ml-1 text-neutral-700">({r.rating || 5}/5)</span>
                        </div>
                      </div>
                      <p className="text-sm text-neutral-700 bg-neutral-50 p-3 rounded border mb-3 font-normal">"{r.comment}"</p>
                      <div className="text-xs text-neutral-500 space-y-0.5">
                        <div><strong>Customer:</strong> {r.user_name} ({r.user_email})</div>
                        <div><strong>Product:</strong> {r.product_name || r.product_id}</div>
                        <div><strong>Submitted:</strong> {new Date(r.created_at || Date.now()).toLocaleString()}</div>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 pt-4 border-t mt-4">
                      {r.status !== 'approved' && (
                        <Button size="sm" onClick={() => handleApproveReview(r.id)} className="bg-emerald-600 hover:bg-emerald-700 text-white font-bold">
                          <CheckCircle2 className="w-4 h-4 mr-1.5" /> Approve & Publish Review
                        </Button>
                      )}
                      {r.status !== 'rejected' && (
                        <Button size="sm" variant="outline" onClick={() => handleRejectReview(r.id)} className="text-amber-700 border-amber-300 hover:bg-amber-50">
                          <XCircle className="w-4 h-4 mr-1.5" /> Reject Review
                        </Button>
                      )}
                      <Button size="sm" variant="outline" onClick={() => handleDeleteReview(r.id)} className="text-red-600 border-red-200 hover:bg-red-50 hover:border-red-300 ml-auto">
                        <Trash2 className="w-4 h-4 mr-1" /> Delete Review
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )
        ) : tab === "settings" ? (
          <div className="bg-white rounded-lg border p-6 max-w-3xl">
            <div className="flex items-center gap-3 mb-6">
              <Settings className="w-6 h-6 text-neutral-400" />
              <div>
                <h2 className="text-xl font-bold">Settings</h2>
                <p className="text-sm text-neutral-500 mt-0.5">Configure store preferences and API keys.</p>
              </div>
            </div>
            <div className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-neutral-700 mb-1">Paystack Public Key</label>
                <Input 
                  value={paystackKey} 
                  onChange={(e) => setPaystackKey(e.target.value)} 
                  placeholder="pk_test_..." 
                  className="font-mono text-sm max-w-sm"
                />
                <p className="text-xs text-neutral-500 mt-1">
                  Required to process real payments via Paystack.
                </p>
              </div>
              
              <div className="pt-6 border-t">
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="text-sm font-bold text-neutral-800">Homepage Top Banners</h3>
                    <p className="text-xs text-neutral-500">Edit the circular category items on the homepage carousel.</p>
                  </div>
                  <Button size="sm" variant="outline" onClick={() => setTopBanners([...topBanners, { id: Math.random().toString(), title: "New Item", image: "https://picsum.photos/seed/new/120/120" }])}>
                    <Plus className="w-4 h-4 mr-1.5" /> Add Banner
                  </Button>
                </div>
                <div className="space-y-3">
                  {topBanners.map((b, i) => (
                    <div key={b.id} className="flex gap-3 items-center bg-neutral-50 p-2 rounded border">
                      <img src={b.image} alt={b.title} className="w-10 h-10 rounded-full bg-white object-cover shadow-sm border" />
                      <div className="flex-1 space-y-1">
                        <Input 
                          value={b.title} 
                          onChange={(e) => {
                            const nb = [...topBanners];
                            nb[i].title = e.target.value;
                            setTopBanners(nb);
                          }} 
                          placeholder="Banner Title" 
                          className="h-8 text-sm bg-white"
                        />
                        <ImageUpload
                          value={b.image}
                          onChange={(url) => {
                            const nb = [...topBanners];
                            nb[i].image = url;
                            setTopBanners(nb);
                          }}
                        />
                      </div>
                      <Button size="icon" variant="ghost" className="text-red-500 hover:text-red-600 hover:bg-red-50 shrink-0" onClick={() => {
                        setTopBanners(topBanners.filter((_, idx) => idx !== i));
                      }}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  ))}
                  {topBanners.length === 0 && (
                    <div className="text-center p-4 text-sm text-neutral-500 bg-neutral-50 rounded border border-dashed">
                      No banners configured. Add one above.
                    </div>
                  )}
                </div>
              </div>
              
              <div className="pt-6 border-t">
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="text-sm font-bold text-neutral-800">Hero Banners</h3>
                    <p className="text-xs text-neutral-500">Edit the sliding banners on the homepage.</p>
                  </div>
                  <Button size="sm" variant="outline" onClick={() => setHeroBanners([...heroBanners, { id: Math.random().toString(), image: "https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?w=1200&h=500&fit=crop", link: "" }])}>
                    <Plus className="w-4 h-4 mr-1.5" /> Add Hero Banner
                  </Button>
                </div>
                <div className="space-y-3">
                  {heroBanners.map((b, i) => (
                    <div key={b.id} className="flex gap-3 items-center bg-neutral-50 p-2 rounded border">
                      <img src={b.image} alt="Hero banner preview" className="w-20 h-10 rounded bg-white object-cover shadow-sm border" />
                      <div className="flex-1 space-y-1">
                        <ImageUpload
                          value={b.image}
                          onChange={(url) => {
                            const nb = [...heroBanners];
                            nb[i].image = url;
                            setHeroBanners(nb);
                          }}
                        />
                        <Input 
                          value={b.link || ""} 
                          onChange={(e) => {
                            const nb = [...heroBanners];
                            nb[i].link = e.target.value;
                            setHeroBanners(nb);
                          }} 
                          placeholder="Banner Link URL (Optional)" 
                          className="h-8 text-sm bg-white"
                        />
                      </div>
                      <Button size="icon" variant="ghost" className="text-red-500 hover:text-red-600 hover:bg-red-50 shrink-0" onClick={() => {
                        setHeroBanners(heroBanners.filter((_, idx) => idx !== i));
                      }}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  ))}
                  {heroBanners.length === 0 && (
                    <div className="text-center p-4 text-sm text-neutral-500 bg-neutral-50 rounded border border-dashed">
                      No hero banners configured. Add one above.
                    </div>
                  )}
                </div>
              </div>

              {/* Tawk.to Live AI Chat Configuration */}
              <div className="pt-6 border-t">
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="text-sm font-bold text-neutral-800">Tawk.to AI Live Chat Channels</h3>
                    <p className="text-xs text-neutral-500">Configure Property IDs for Admin-Buyer and Vendor-Admin chats.</p>
                  </div>
                </div>
                <div className="grid md:grid-cols-2 gap-4 bg-neutral-50 p-4 rounded-xl border">
                  <div className="space-y-2">
                    <label className="text-xs font-semibold text-neutral-700 block">Channel 1: Admin & Buyer Tawk Property</label>
                    <Input
                      placeholder="e.g. 600000000000000000000000"
                      defaultValue={localStorage.getItem("tawk_property_admin-buyer") || ""}
                      onChange={(e) => localStorage.setItem("tawk_property_admin-buyer", e.target.value)}
                      className="text-xs bg-white"
                    />
                    <Input
                      placeholder="Widget ID e.g. 1f0000000"
                      defaultValue={localStorage.getItem("tawk_widget_admin-buyer") || ""}
                      onChange={(e) => localStorage.setItem("tawk_widget_admin-buyer", e.target.value)}
                      className="text-xs bg-white"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-xs font-semibold text-neutral-700 block">Channel 2: Vendor & Admin Tawk Property</label>
                    <Input
                      placeholder="e.g. 600000000000000000000001"
                      defaultValue={localStorage.getItem("tawk_property_vendor-admin") || ""}
                      onChange={(e) => localStorage.setItem("tawk_property_vendor-admin", e.target.value)}
                      className="text-xs bg-white"
                    />
                    <Input
                      placeholder="Widget ID e.g. 1f0000001"
                      defaultValue={localStorage.getItem("tawk_widget_vendor-admin") || ""}
                      onChange={(e) => localStorage.setItem("tawk_widget_vendor-admin", e.target.value)}
                      className="text-xs bg-white"
                    />
                  </div>
                </div>
              </div>

            </div>
          </div>
        ) : tab === "reviews" ? (
          <div className="bg-white rounded-xl border p-6 space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b pb-4">
              <div>
                <h2 className="text-xl font-bold flex items-center gap-2">
                  <Video className="w-5 h-5 text-orange-500" /> Customer Video Reviews Moderation
                </h2>
                <p className="text-xs text-neutral-500 mt-1">
                  Reviews must be confirmed by Admin before they appear on vendor storefronts and product pages.
                </p>
              </div>
              <Button size="sm" variant="outline" onClick={fetchAdminReviews} className="text-xs shrink-0">
                Refresh Reviews
              </Button>
            </div>

            {adminReviews.length === 0 ? (
              <div className="text-center py-12 text-neutral-500 text-sm">
                <Video className="w-12 h-12 text-neutral-300 mx-auto mb-3" />
                No customer video reviews submitted yet.
              </div>
            ) : (
              <div className="space-y-4">
                {adminReviews.map((rev) => {
                  const revStatus = rev.status || 'pending';
                  const isApproved = revStatus === 'approved';
                  const isRejected = revStatus === 'rejected';

                  return (
                    <div key={rev.id} className="border rounded-xl p-4 bg-neutral-50/50 flex flex-col sm:flex-row gap-4 items-start hover:border-neutral-300 transition">
                      {/* Video Player */}
                      <div className="w-full sm:w-56 shrink-0">
                        {rev.video_url ? (
                          <video
                            src={rev.video_url}
                            controls
                            className="w-full h-36 object-cover rounded-lg bg-black shadow-sm border"
                          />
                        ) : (
                          <div className="w-full h-36 bg-neutral-200 rounded-lg flex items-center justify-center text-xs text-neutral-500">
                            No Video File
                          </div>
                        )}
                      </div>

                      {/* Content Details */}
                      <div className="flex-1 space-y-2 text-xs">
                        <div className="flex flex-wrap items-start justify-between gap-2">
                          <div>
                            <div className="font-bold text-sm text-neutral-900">
                              {rev.product_name || `Product: ${rev.product_id}`}
                            </div>
                            <div className="text-neutral-500 mt-0.5">
                              Submitted by <strong className="text-neutral-800">{rev.user_name}</strong> ({rev.user_email}) · Order {rev.order_id}
                            </div>
                          </div>

                          <span className={`text-[11px] px-2.5 py-0.5 rounded-full font-bold uppercase border ${
                            isApproved 
                              ? 'bg-emerald-50 text-emerald-700 border-emerald-200' 
                              : isRejected 
                              ? 'bg-red-50 text-red-700 border-red-200' 
                              : 'bg-amber-50 text-amber-700 border-amber-200'
                          }`}>
                            {isApproved ? 'Approved & Public' : isRejected ? 'Rejected' : 'Pending Confirmation'}
                          </span>
                        </div>

                        {/* Rating Stars */}
                        <div className="flex items-center gap-1">
                          {[1, 2, 3, 4, 5].map((s) => (
                            <Star
                              key={s}
                              className={`w-3.5 h-3.5 ${s <= (rev.rating || 5) ? 'text-amber-400 fill-amber-400' : 'text-neutral-300'}`}
                            />
                          ))}
                          <span className="ml-1 text-[11px] font-bold text-neutral-600">{rev.rating || 5}/5 Stars</span>
                        </div>

                        {/* Review Title & Comment */}
                        <div className="bg-white p-3 rounded-lg border text-xs space-y-1">
                          <div className="font-bold text-neutral-900">{rev.title}</div>
                          <p className="text-neutral-600 leading-relaxed">{rev.comment}</p>
                        </div>

                        {/* Admin Moderation Actions */}
                        <div className="pt-2 flex flex-wrap gap-2 items-center">
                          {!isApproved && (
                            <Button
                              size="sm"
                              onClick={() => handleApproveReview(rev.id)}
                              className="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs gap-1.5 h-8"
                            >
                              <CheckCircle2 className="w-3.5 h-3.5" /> Approve & Publish Review
                            </Button>
                          )}
                          {!isRejected && (
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleRejectReview(rev.id)}
                              className="border-red-300 text-red-600 hover:bg-red-50 text-xs gap-1.5 h-8"
                            >
                              <XCircle className="w-3.5 h-3.5" /> Reject Review
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        ) : null}
      </main>

      <Dialog open={!!viewVendor} onOpenChange={(o) => !o && setViewVendor(null)}>
        <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Vendor Details: {viewVendor?.businessName}</DialogTitle>
          </DialogHeader>
          {viewVendor && (
            <div className="grid grid-cols-2 gap-4 text-sm mt-4">
              <div><span className="text-neutral-500 block text-xs">Business Type</span>{viewVendor.businessType}</div>
              <div><span className="text-neutral-500 block text-xs">Category</span>{viewVendor.category}</div>
              <div><span className="text-neutral-500 block text-xs">RC Number</span>{viewVendor.rcNumber || "-"}</div>
              <div><span className="text-neutral-500 block text-xs">Tax ID</span>{viewVendor.taxId || "-"}</div>
              <div><span className="text-neutral-500 block text-xs">Contact Name</span>{viewVendor.contactName}</div>
              <div><span className="text-neutral-500 block text-xs">Contact Email</span>{viewVendor.contactEmail}</div>
              <div><span className="text-neutral-500 block text-xs">Contact Phone</span>{viewVendor.contactPhone}</div>
              <div><span className="text-neutral-500 block text-xs">Address</span>{viewVendor.address}, {viewVendor.city}, {viewVendor.state}</div>
              <div>
                <span className="text-neutral-500 block text-xs">GPS Location</span>
                {viewVendor.lat && viewVendor.lng ? (
                  <a href={`https://www.google.com/maps/search/?api=1&query=${viewVendor.lat},${viewVendor.lng}`} target="_blank" rel="noreferrer" className="text-orange-500 hover:underline">
                    View on Map ({viewVendor.lat.toFixed(4)}, {viewVendor.lng.toFixed(4)})
                  </a>
                ) : "-"}
              </div>
              <div><span className="text-neutral-500 block text-xs">Bank Name</span>{viewVendor.bankName}</div>
              <div><span className="text-neutral-500 block text-xs">Account Name</span>{viewVendor.accountName}</div>
              <div><span className="text-neutral-500 block text-xs">Account Number</span>{viewVendor.accountNumber}</div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      <Dialog open={!!editVendor} onOpenChange={(o) => !o && setEditVendor(null)}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Edit Vendor</DialogTitle>
          </DialogHeader>
          {editVendor && <EditVendorForm vendor={editVendor} onClose={() => setEditVendor(null)} onSave={adminEditVendor} />}
        </DialogContent>
      </Dialog>
    </div>
  );
}
