"use client";
import React, { useState, useMemo } from "react";
import Link from "next/link";
import { Search, Package, Edit, Trash, Grid, List, Plus, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { deleteProduct } from "@/app/actions/product";
import { toast } from "sonner";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { PageHeader } from "@/components/page-header";
import { useRouter } from "next/navigation";

const STATUS_MAP: Record<string, { label: string; className: string }> = {
  PUBLISHED: { label: "منتشر شده", className: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400" },
  DRAFT: { label: "پیش‌نویس", className: "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" },
  HIDDEN: { label: "مخفی", className: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400" },
  ARCHIVED: { label: "آرشیو", className: "bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400" },
};

export function ProductsClient({ initialData, categories }: { initialData: any[]; categories: any[] }) {
  const [products, setProducts] = useState(initialData);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("ALL");
  const [filterCategory, setFilterCategory] = useState("ALL");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const filtered = useMemo(() => {
    return products.filter(p => {
      const matchSearch = !searchTerm || p.title.includes(searchTerm) || (p.sku && p.sku.includes(searchTerm));
      const matchStatus = filterStatus === "ALL" || p.status === filterStatus;
      const matchCat = filterCategory === "ALL" || p.categories?.some((c: any) => c.categoryId === filterCategory);
      return matchSearch && matchStatus && matchCat;
    });
  }, [products, searchTerm, filterStatus, filterCategory]);

  const handleDelete = async (id: string) => {
    const res = await deleteProduct(id);
    if (res.success) {
      setProducts(prev => prev.filter(p => p.id !== id));
      toast.success("محصول با موفقیت حذف شد.");
    } else {
      toast.error(res.error || "خطا در حذف");
    }
    setDeleteId(null);
  };

  const router = useRouter();

  return (
    <div className="flex flex-col h-full overflow-hidden" dir="rtl">
      <PageHeader
        title="مدیریت محصولات"
        subtitle={`${products.length} محصول ثبت شده`}
        icon={<Package className="w-4 h-4" />}
        actions={[
          { label: viewMode === "grid" ? "نمای لیست" : "نمای شبکه", icon: viewMode === "grid" ? <List className="w-4 h-4" /> : <Grid className="w-4 h-4" />, onClick: () => setViewMode(viewMode === "grid" ? "list" : "grid"), variant: "outline" },
          { label: "افزودن محصول", icon: <Plus className="w-4 h-4" />, onClick: () => router.push("/admin/products/add"), variant: "default", className: "bg-indigo-600 hover:bg-indigo-700 text-white" },
        ]}
      />

      <div className="flex-1 overflow-auto p-4 md:p-5 space-y-4">
      <div className="flex flex-col sm:flex-row gap-3 bg-card p-4 rounded-xl border shadow-sm">
        <div className="relative flex-1">
          <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input placeholder="جستجو بر اساس نام، کد یا بارکد..." className="pr-9" value={searchTerm} onChange={e => setSearchTerm(e.target.value)} />
        </div>
        <Select value={filterStatus} onValueChange={setFilterStatus}>
          <SelectTrigger className="w-full sm:w-44"><SelectValue placeholder="وضعیت" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="ALL">همه وضعیت‌ها</SelectItem>
            <SelectItem value="PUBLISHED">منتشر شده</SelectItem>
            <SelectItem value="DRAFT">پیش‌نویس</SelectItem>
            <SelectItem value="HIDDEN">مخفی</SelectItem>
            <SelectItem value="ARCHIVED">آرشیو</SelectItem>
          </SelectContent>
        </Select>
        <Select value={filterCategory} onValueChange={setFilterCategory}>
          <SelectTrigger className="w-full sm:w-44"><SelectValue placeholder="دسته‌بندی" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="ALL">همه دسته‌بندی‌ها</SelectItem>
            {categories.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}
          </SelectContent>
        </Select>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "کل محصولات", value: products.length, color: "text-indigo-600" },
          { label: "منتشر شده", value: products.filter(p => p.status === "PUBLISHED").length, color: "text-emerald-600" },
          { label: "پیش‌نویس", value: products.filter(p => p.status === "DRAFT").length, color: "text-amber-600" },
          { label: "موجودی کم", value: products.filter(p => p.manageStock && p.stockQuantity !== null && p.lowStockThreshold && p.stockQuantity <= p.lowStockThreshold).length, color: "text-rose-600" },
        ].map(s => (
          <div key={s.label} className="bg-card border rounded-xl p-4 shadow-sm">
            <div className={`text-2xl font-black font-sans ${s.color}`}>{s.value}</div>
            <div className="text-xs text-muted-foreground mt-1">{s.label}</div>
          </div>
        ))}
      </div>

      {/* Products Grid / List */}
      {filtered.length === 0 ? (
        <div className="py-20 text-center text-muted-foreground bg-muted/20 rounded-xl border-2 border-dashed">
          <Package className="w-12 h-12 mx-auto mb-4 opacity-30" />
          <p>محصولی با این فیلترها یافت نشد.</p>
          <Button asChild className="mt-4" variant="outline"><Link href="/admin/products/add">افزودن اولین محصول</Link></Button>
        </div>
      ) : viewMode === "grid" ? (
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-5 gap-4">
          {filtered.map(product => (
            <div key={product.id} className="bg-card border rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all group flex flex-col">
              <div className="aspect-square bg-muted/30 relative flex items-center justify-center overflow-hidden">
                {product.images?.[0] ? (
                  <img src={product.images[0].imageUrl} alt={product.title} className="object-cover w-full h-full group-hover:scale-105 transition-transform duration-300" />
                ) : (
                  <Package className="w-12 h-12 text-muted-foreground/20" />
                )}
                <div className="absolute top-2 right-2">
                  <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-md shadow-sm ${STATUS_MAP[product.status]?.className}`}>
                    {STATUS_MAP[product.status]?.label}
                  </span>
                </div>
                {product.manageStock && product.stockQuantity !== null && product.stockQuantity <= (product.lowStockThreshold || 5) && (
                  <div className="absolute top-2 left-2">
                    <AlertCircle className="w-4 h-4 text-rose-500" />
                  </div>
                )}
              </div>
              <div className="p-3 flex flex-col flex-1 gap-2">
                <h3 className="font-semibold text-sm line-clamp-2 leading-snug">{product.title}</h3>
                <div className="flex items-center justify-between text-xs text-muted-foreground">
                  <span className="font-sans">{(product.price || 0).toLocaleString("fa-IR")}</span>
                  {product.salePrice && <span className="text-rose-500 font-sans line-through">{product.salePrice.toLocaleString("fa-IR")}</span>}
                </div>
                <div className="flex items-center gap-1 text-xs text-muted-foreground">
                  {product.manageStock && <Package className="w-3 h-3" />}
                  {product.manageStock && <span className="font-sans">{product.stockQuantity ?? 0} عدد</span>}
                </div>
                <div className="flex gap-1 mt-auto">
                  <Button asChild variant="outline" size="sm" className="flex-1 text-xs h-8">
                    <Link href={`/admin/products/${product.id}/edit`}><Edit className="w-3 h-3 ml-1" />ویرایش</Link>
                  </Button>
                  <Button variant="ghost" size="sm" className="h-8 px-2 text-rose-500 hover:text-rose-600 hover:bg-rose-50" onClick={() => setDeleteId(product.id)}>
                    <Trash className="w-3.5 h-3.5" />
                  </Button>
                </div>
                
                <div className="text-[10px] text-muted-foreground border-t pt-2 mt-auto flex flex-col gap-1">
                  <div className="flex justify-between">
                    <span>ثبت:</span>
                    <span className="font-sans" dir="ltr">{product.createdBy ? (product.createdBy.fullName || product.createdBy.phone) : "سیستم"} - {new Date(product.createdAt).toLocaleDateString("fa-IR")}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>آخرین ویرایش:</span>
                    <span className="font-sans" dir="ltr">{product.updatedBy ? (product.updatedBy.fullName || product.updatedBy.phone) : "سیستم"} - {new Date(product.updatedAt).toLocaleDateString("fa-IR")}</span>
                  </div>
                </div>
                
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="bg-card border rounded-xl shadow-sm overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 border-b">
              <tr>
                <th className="text-right p-4 font-semibold">محصول</th>
                <th className="text-right p-4 font-semibold hidden sm:table-cell">وضعیت</th>
                <th className="text-right p-4 font-semibold hidden md:table-cell">قیمت (تومان)</th>
                <th className="text-right p-4 font-semibold hidden md:table-cell">موجودی</th>
                <th className="text-right p-4 font-semibold hidden lg:table-cell">ثبت / ویرایش</th>
                <th className="text-left p-4 font-semibold">عملیات</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map(product => (
                <tr key={product.id} className="hover:bg-muted/20 transition-colors">
                  <td className="p-4">
                    <div className="flex items-center gap-3">
                      <div className="w-12 h-12 bg-muted rounded-lg overflow-hidden shrink-0">
                        {product.images?.[0] ? (
                          <img src={product.images[0].imageUrl} alt={product.title} className="object-cover w-full h-full" />
                        ) : <Package className="w-6 h-6 m-3 text-muted-foreground/30" />}
                      </div>
                      <div>
                        <div className="font-semibold line-clamp-1">{product.title}</div>
                        <div className="text-xs text-muted-foreground font-sans">{product.sku || "-"}</div>
                      </div>
                    </div>
                  </td>
                  <td className="p-4 hidden sm:table-cell">
                    <span className={`text-xs font-bold px-2 py-1 rounded-md ${STATUS_MAP[product.status]?.className}`}>
                      {STATUS_MAP[product.status]?.label}
                    </span>
                  </td>
                  <td className="p-4 font-sans hidden md:table-cell">{(product.price || 0).toLocaleString("fa-IR")}</td>
                  <td className="p-4 hidden md:table-cell">
                    {product.manageStock ? (
                      <span className={`font-sans font-bold ${product.stockQuantity <= (product.lowStockThreshold || 5) ? "text-rose-500" : "text-emerald-600"}`}>
                        {product.stockQuantity ?? 0}
                      </span>
                    ) : <span className="text-muted-foreground text-xs">نامحدود</span>}
                  </td>
                  <td className="p-4 hidden lg:table-cell">
                    <div className="flex flex-col gap-1 text-[10px] text-muted-foreground">
                      <div>
                        <span className="font-bold text-slate-700 dark:text-slate-300">ثبت:</span> {product.createdBy ? ((product.createdBy.firstName ? product.createdBy.firstName + ' ' + product.createdBy.lastName : product.createdBy.mobile)) : "سیستم"} <span className="font-sans">({new Date(product.createdAt).toLocaleDateString("fa-IR")})</span>
                      </div>
                      <div>
                        <span className="font-bold text-slate-700 dark:text-slate-300">ویرایش:</span> {product.updatedBy ? ((product.updatedBy.firstName ? product.updatedBy.firstName + ' ' + product.updatedBy.lastName : product.updatedBy.mobile)) : "سیستم"} <span className="font-sans">({new Date(product.updatedAt).toLocaleDateString("fa-IR")})</span>
                      </div>
                    </div>
                  </td>
                  <td className="p-4">
                    <div className="flex items-center gap-2 justify-end">
                      <Button asChild variant="outline" size="sm"><Link href={`/admin/products/${product.id}/edit`}><Edit className="w-3 h-3 ml-1" />ویرایش</Link></Button>
                      <Button variant="ghost" size="icon" className="text-rose-500 h-8 w-8" onClick={() => setDeleteId(product.id)}><Trash className="w-4 h-4" /></Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <AlertDialog open={!!deleteId} onOpenChange={open => !open && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف محصول</AlertDialogTitle>
            <AlertDialogDescription>آیا از حذف این محصول اطمینان دارید؟ این عمل غیرقابل بازگشت است.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>انصراف</AlertDialogCancel>
            <AlertDialogAction className="bg-destructive text-destructive-foreground" onClick={() => deleteId && handleDelete(deleteId)}>حذف</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      </div>
    </div>
  );
}
