"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { PageHeader } from "@/components/page-header";
import { ResponsiveModal } from "@/components/ui/responsive-modal";
import { toast } from "sonner";
import { Plus, Edit, Trash, Tag, ChevronRight, ImageIcon } from "lucide-react";
import { createCategory, updateCategory, deleteCategory } from "@/app/actions/category";
import MediaManager, { MediaPicked } from "@/components/media/media-manager";

export function CategoriesClient({ initialData }: { initialData: any[] }) {
  const [categories, setCategories] = useState(initialData);
  const [isOpen, setIsOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [form, setForm] = useState({ name: "", slug: "", description: "", parentId: "", imageMediaId: "" });
  const [selectedMedia, setSelectedMedia] = useState<MediaPicked | null>(null);

  const openAdd = () => { setEditing(null); setForm({ name: "", slug: "", description: "", parentId: "", imageMediaId: "" }); setSelectedMedia(null); setIsOpen(true); };
  const openEdit = (cat: any) => { setEditing(cat); setForm({ name: cat.name, slug: cat.slug, description: cat.description || "", parentId: cat.parentId || "", imageMediaId: cat.imageMediaId || "" }); setSelectedMedia(cat.imageMedia ? { id: cat.imageMedia.id, url: cat.imageMedia.url } as any : null); setIsOpen(true); };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name) return toast.error("نام دسته‌بندی الزامی است.");
    const payload = { ...form, parentId: form.parentId || null, imageMediaId: selectedMedia?.id || null };
    if (editing) {
      const res = await updateCategory(editing.id, payload);
      if (res.success) { setCategories(p => p.map(c => c.id === editing.id ? { ...c, ...payload } : c)); toast.success("ویرایش شد."); setIsOpen(false); }
      else toast.error(res.error);
    } else {
      const res = await createCategory(payload);
      if (res.success) { setCategories(p => [...p, res.category]); toast.success("دسته‌بندی ایجاد شد."); setIsOpen(false); }
      else toast.error(res.error);
    }
  };

  const handleDelete = async (id: string) => {
    const res = await deleteCategory(id);
    if (res.success) { setCategories(p => p.filter(c => c.id !== id)); toast.success("دسته‌بندی حذف شد."); }
    else toast.error(res.error || "خطا در حذف");
    setDeleteId(null);
  };

  const roots = categories.filter(c => !c.parentId);
  const getChildren = (parentId: string) => categories.filter(c => c.parentId === parentId);

  const renderSelectItems = (parentId: string | null, depth = 0): React.ReactNode[] => {
    return categories
      .filter(c => c.parentId === parentId && c.id !== editing?.id)
      .flatMap(c => [
        <SelectItem key={c.id} value={c.id}>
          {"—".repeat(depth)} {c.name}
        </SelectItem>,
        ...renderSelectItems(c.id, depth + 1)
      ]);
  };

  const renderCategoryNode = (cat: any, depth = 0) => {
    const children = getChildren(cat.id);
    return (
      <div key={cat.id} className={`${depth === 0 ? 'bg-card border rounded-xl shadow-sm mb-3' : 'border-t border-dashed bg-muted/5'} overflow-hidden`}>
        <div className={`flex items-center justify-between p-4 hover:bg-muted/20`} style={{ paddingRight: depth === 0 ? '1rem' : `${depth * 1.5 + 1}rem` }}>
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-indigo-100 dark:bg-indigo-900/30 rounded-full flex items-center justify-center text-indigo-600">
              <Tag className="w-4 h-4" />
            </div>
            <div>
              <div className="font-bold">{cat.name}</div>
              <div className="text-xs text-muted-foreground font-sans">{cat.slug}</div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="flex flex-col text-[10px] text-muted-foreground ml-4 hidden md:flex border-l pl-4 border-muted">
              <span className="font-sans" dir="ltr">{cat.createdBy ? (cat.createdBy.fullName || cat.createdBy.phone) : "سیستم"} - {new Date(cat.createdAt).toLocaleDateString("fa-IR")}</span>
              <div className="flex justify-between">
                <span>آخرین ویرایش:</span>
                <span className="font-sans" dir="ltr">{cat.updatedBy ? (cat.updatedBy.fullName || cat.updatedBy.phone) : "سیستم"} - {new Date(cat.updatedAt).toLocaleDateString("fa-IR")}</span>
              </div>
            </div>
            <Badge variant="secondary" className="font-sans mr-4">{cat._count?.products || 0} محصول</Badge>
            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(cat)}><Edit className="w-4 h-4" /></Button>
            <Button variant="ghost" size="icon" className="h-8 w-8 text-rose-500" onClick={() => setDeleteId(cat.id)}><Trash className="w-4 h-4" /></Button>
          </div>
        </div>
        {children.length > 0 && (
          <div className="flex flex-col">
            {children.map(child => renderCategoryNode(child, depth + 1))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="flex flex-col h-full" dir="rtl">
      <PageHeader
        title="دسته‌بندی‌ها"
        subtitle={`${categories.length} دسته‌بندی تعریف شده`}
        icon={<Tag className="w-5 h-5" />}
        actions={[
          { label: "دسته‌بندی جدید", icon: <Plus className="w-4 h-4" />, onClick: openAdd, 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-3">
        {roots.length === 0 && (
          <div className="py-16 text-center text-muted-foreground border-2 border-dashed rounded-xl">
            <Tag className="w-10 h-10 mx-auto mb-3 opacity-20" />
            <p>هنوز دسته‌بندی ایجاد نشده است.</p>
            <Button variant="outline" className="mt-4" onClick={openAdd}>ایجاد اولین دسته‌بندی</Button>
          </div>
        )}
        {roots.map(cat => renderCategoryNode(cat, 0))}
      </div>

      <ResponsiveModal open={isOpen} onOpenChange={setIsOpen} title={editing ? "ویرایش دسته‌بندی" : "دسته‌بندی جدید"}>
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          <div className="space-y-2">
            <Label>نام دسته‌بندی *</Label>
            <Input value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} placeholder="مثال: موبایل و تبلت" required />
          </div>
          <div className="space-y-2">
            <Label>Slug</Label>
            <Input dir="ltr" className="text-left font-sans" value={form.slug} onChange={e => setForm(p => ({ ...p, slug: e.target.value }))} placeholder="mobile-tablet" />
          </div>
          <div className="space-y-2">
            <Label>دسته‌بندی والد</Label>
            <Select value={form.parentId || "none"} onValueChange={v => setForm(p => ({ ...p, parentId: v === "none" ? "" : v }))}>
              <SelectTrigger><SelectValue placeholder="بدون والد (اصلی)" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">بدون والد (دسته اصلی)</SelectItem>
                {renderSelectItems(null)}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>توضیحات</Label>
            <Textarea rows={2} value={form.description} onChange={e => setForm(p => ({ ...p, description: e.target.value }))} />
          </div>
          <div className="space-y-2">
            <Label>تصویر دسته‌بندی</Label>
            <MediaManager
                mode="single"
                value={selectedMedia}
                onChange={(m) => setSelectedMedia(m as MediaPicked | null)}
                triggerLabel={selectedMedia ? "تغییر تصویر" : "انتخاب تصویر"}
                title="انتخاب تصویر دسته‌بندی"
            />
            {selectedMedia && (
                <div className="mt-2 relative inline-block border rounded-md p-1 bg-muted/20">
                    <img src={selectedMedia.url} className="h-16 object-contain rounded" />
                </div>
            )}
          </div>
          <div className="flex gap-3 pt-2">
            <Button type="button" variant="outline" className="flex-1" onClick={() => setIsOpen(false)}>انصراف</Button>
            <Button type="submit" className="flex-1 bg-indigo-600 hover:bg-indigo-700">{editing ? "ذخیره تغییرات" : "ایجاد دسته‌بندی"}</Button>
          </div>
        </form>
      </ResponsiveModal>

      <AlertDialog open={!!deleteId} onOpenChange={open => !open && setDeleteId(null)}>
        <AlertDialogContent dir="rtl">
          <AlertDialogHeader>
            <AlertDialogTitle>حذف دسته‌بندی</AlertDialogTitle>
            <AlertDialogDescription>آیا مطمئن هستید؟ دسته‌بندی‌های زیرمجموعه جدا می‌شوند.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter className="flex-row-reverse gap-2">
            <AlertDialogCancel>انصراف</AlertDialogCancel>
            <AlertDialogAction className="bg-destructive" onClick={() => deleteId && handleDelete(deleteId)}>حذف</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
