"use client";
import { useState } from "react";
import { PageHeader } from "@/components/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ResponsiveModal } from "@/components/ui/responsive-modal";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { Plus, Edit, Trash2, Sliders, X, Palette, ChevronDown, ChevronUp } from "lucide-react";
import {
  createAttribute, updateAttribute, deleteAttribute,
  createAttributeValue, deleteAttributeValue,
} from "@/app/actions/attribute";

const INPUT_TYPES: Record<string, { label: string; hint: string }> = {
  TEXT:        { label: "متن آزاد",     hint: "برای مشخصاتی مثل کشور سازنده، مواد تشکیل دهنده" },
  NUMBER:      { label: "عدد",           hint: "برای وزن، ابعاد، ظرفیت" },
  SELECT:      { label: "انتخابی",       hint: "یک مقدار از لیست - مثل سایز" },
  MULTISELECT: { label: "چند انتخابی",  hint: "چند مقدار - مثل رنگ‌های موجود" },
  COLOR:       { label: "رنگ",           hint: "مقادیر با کد HEX - نمایش رنگ در گالری" },
  BOOLEAN:     { label: "بله/خیر",       hint: "برای ویژگی‌های دوحالته" },
};

export default function AttributesClient({ initialData }: { initialData: any[] }) {
  const [attributes, setAttributes] = useState(initialData);
  const [isOpen, setIsOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [form, setForm] = useState({ name: "", slug: "", inputType: "SELECT", isVariantable: false, isFilterable: true });
  const [newVal, setNewVal] = useState({ value: "", colorHex: "" });
  const [addingValueTo, setAddingValueTo] = useState<string | null>(null);

  const openAdd = () => {
    setEditing(null);
    setForm({ name: "", slug: "", inputType: "SELECT", isVariantable: false, isFilterable: true });
    setIsOpen(true);
  };
  const openEdit = (attr: any) => {
    setEditing(attr);
    setForm({ name: attr.name, slug: attr.slug, inputType: attr.inputType, isVariantable: attr.isVariantable, isFilterable: attr.isFilterable });
    setIsOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim()) return toast.error("نام ویژگی الزامی است.");
    if (editing) {
      const res = await updateAttribute(editing.id, { name: form.name, inputType: form.inputType });
      if (res.success) {
        setAttributes(p => p.map(a => a.id === editing.id ? { ...a, ...form } : a));
        toast.success("ویرایش شد."); setIsOpen(false);
      } else toast.error(res.error);
    } else {
      const res = await createAttribute({ name: form.name, slug: form.slug, inputType: form.inputType, isFilterable: form.isFilterable, isVariantable: form.isVariantable });
      if (res.success && res.attribute) {
        setAttributes(p => [...p, { ...res.attribute!, values: [], _count: { productAttributes: 0 } }]);
        toast.success("ویژگی ایجاد شد."); setIsOpen(false);
      } else toast.error(res.error);
    }
  };

  const handleAddValue = async (attrId: string) => {
    if (!newVal.value.trim()) return toast.error("مقدار الزامی است.");
    const res = await createAttributeValue(attrId, { value: newVal.value, colorHex: newVal.colorHex || undefined });
    if (res.success && res.value) {
      setAttributes(p => p.map(a => a.id === attrId ? { ...a, values: [...a.values, res.value!] } : a));
      setNewVal({ value: "", colorHex: "" });
      setAddingValueTo(null);
      toast.success("مقدار اضافه شد.");
    } else toast.error(res.error);
  };

  const handleDeleteValue = async (attrId: string, valId: string) => {
    const res = await deleteAttributeValue(valId);
    if (res.success) {
      setAttributes(p => p.map(a => a.id === attrId ? { ...a, values: a.values.filter((v: any) => v.id !== valId) } : a));
      toast.success("حذف شد.");
    } else toast.error(res.error);
  };

  const handleDelete = async (id: string) => {
    const res = await deleteAttribute(id);
    if (res.success) { setAttributes(p => p.filter(a => a.id !== id)); toast.success("ویژگی حذف شد."); }
    else toast.error(res.error || "خطا در حذف");
    setDeleteId(null);
  };

  const currentAttr = attributes.find(a => a.id === addingValueTo);

  return (
    <div className="flex flex-col h-full" dir="rtl">
      <PageHeader
        title="ویژگی‌های محصولات"
        subtitle="مدیریت ویژگی‌ها، آتریبوت‌ها و مقادیر (رنگ، سایز، ...)"
        icon={<Sliders 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">
        {attributes.length === 0 ? (
          <div className="border-2 border-dashed rounded-xl py-16 text-center text-muted-foreground">
            <Sliders className="w-10 h-10 mx-auto mb-3 opacity-20" />
            <p className="mb-4">هنوز ویژگی‌ای تعریف نشده است.</p>
            <Button variant="outline" onClick={openAdd}>ایجاد اولین ویژگی</Button>
          </div>
        ) : attributes.map(attr => (
          <div key={attr.id} className="bg-card border rounded-xl shadow-sm overflow-hidden">
            <div
              className="flex items-center justify-between p-4 cursor-pointer hover:bg-muted/20 transition-colors"
              onClick={() => setExpandedId(expandedId === attr.id ? null : attr.id)}
            >
              <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">
                  {attr.inputType === "COLOR" ? <Palette className="w-4 h-4" /> : <Sliders className="w-4 h-4" />}
                </div>
                <div>
                  <div className="font-bold flex items-center gap-2">
                    {attr.name}
                    {attr.isVariantable && <Badge variant="secondary" className="text-[10px] px-1.5">واریانت‌ساز</Badge>}
                    {attr.isFilterable && <Badge variant="outline" className="text-[10px] px-1.5">فیلتر</Badge>}
                  </div>
                  <div className="text-xs text-muted-foreground flex items-center gap-2 mt-0.5">
                    <Badge variant="outline" className="text-[10px]">{INPUT_TYPES[attr.inputType]?.label || attr.inputType}</Badge>
                    <span className="font-sans text-muted-foreground/60">{attr.slug}</span>
                    <span>{attr.values?.length || 0} مقدار</span>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
                <div className="flex flex-col text-[10px] text-muted-foreground ml-4 hidden md:flex border-l pl-4 border-muted">
                  <div><span className="font-bold text-slate-700 dark:text-slate-300">ثبت:</span> <span className="font-sans" dir="ltr">{attr.createdBy ? (attr.createdBy.fullName || attr.createdBy.phone) : "سیستم"} - {new Date(attr.createdAt).toLocaleDateString("fa-IR")}</span></div>
                  <div><span className="font-bold text-slate-700 dark:text-slate-300">ویرایش:</span> <span className="font-sans" dir="ltr">{attr.updatedBy ? (attr.updatedBy.fullName || attr.updatedBy.phone) : "سیستم"} - {new Date(attr.updatedAt).toLocaleDateString("fa-IR")}</span></div>
                </div>
                <Badge variant="secondary" className="font-sans hidden sm:flex">{attr._count?.productAttributes || 0} محصول</Badge>
                <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(attr)}><Edit className="w-4 h-4" /></Button>
                <Button variant="ghost" size="icon" className="h-8 w-8 text-rose-500" onClick={() => setDeleteId(attr.id)}><Trash2 className="w-4 h-4" /></Button>
                {expandedId === attr.id ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />}
              </div>
            </div>

            {expandedId === attr.id && (
              <div className="border-t bg-muted/10 p-4 space-y-3">
                <p className="text-xs text-muted-foreground">{INPUT_TYPES[attr.inputType]?.hint}</p>
                <div className="flex flex-wrap gap-2">
                  {attr.values?.map((val: any) => (
                    <div key={val.id} className="flex items-center gap-1.5 bg-card border rounded-lg px-3 py-1.5 shadow-sm group">
                      {attr.inputType === "COLOR" && val.colorHex && (
                        <div className="w-4 h-4 rounded-full border shadow-sm shrink-0" style={{ background: val.colorHex }} />
                      )}
                      <span className="text-sm font-medium">{val.value}</span>
                      {val.colorHex && attr.inputType === "COLOR" && (
                        <span className="text-[10px] text-muted-foreground font-sans">{val.colorHex}</span>
                      )}
                      <button
                        onClick={() => handleDeleteValue(attr.id, val.id)}
                        className="text-rose-400 hover:text-rose-600 opacity-0 group-hover:opacity-100 transition-opacity ml-1"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </div>
                  ))}
                  {(["SELECT","MULTISELECT","COLOR"].includes(attr.inputType)) && (
                    <Button size="sm" variant="outline" className="h-8 border-dashed gap-1 text-xs"
                      onClick={() => { setAddingValueTo(attr.id); setNewVal({ value: "", colorHex: "" }); }}>
                      <Plus className="w-3 h-3" /> افزودن مقدار
                    </Button>
                  )}
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Add/Edit Modal */}
      <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>نوع ورودی</Label>
            <Select value={form.inputType} onValueChange={v => setForm(p => ({ ...p, inputType: v }))}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                {Object.entries(INPUT_TYPES).map(([v, t]) => (
                  <SelectItem key={v} value={v}>
                    <div><span className="font-medium">{t.label}</span><span className="text-xs text-muted-foreground mr-2">{t.hint.slice(0, 30)}...</span></div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          {!editing && (
            <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="color" />
            </div>
          )}
          <div className="flex gap-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <Switch checked={form.isVariantable} onCheckedChange={v => setForm(p => ({ ...p, isVariantable: v }))} />
              <span className="text-sm">واریانت‌ساز</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <Switch checked={form.isFilterable} onCheckedChange={v => setForm(p => ({ ...p, isFilterable: v }))} />
              <span className="text-sm">قابل فیلتر</span>
            </label>
          </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>

      {/* Add Value Modal */}
      <ResponsiveModal open={!!addingValueTo} onOpenChange={v => !v && setAddingValueTo(null)} title={`افزودن مقدار به: ${currentAttr?.name || ""}`}>
        <div className="p-4 space-y-4">
          <div className="space-y-2">
            <Label>مقدار *</Label>
            <Input value={newVal.value} onChange={e => setNewVal(p => ({ ...p, value: e.target.value }))} placeholder="مثال: قرمز، XL، ایران" />
          </div>
          {currentAttr?.inputType === "COLOR" && (
            <div className="space-y-2">
              <Label>کد رنگ HEX</Label>
              <div className="flex gap-2 items-center">
                <input type="color" className="w-12 h-10 rounded-lg border cursor-pointer p-1"
                  value={newVal.colorHex || "#000000"} onChange={e => setNewVal(p => ({ ...p, colorHex: e.target.value }))} />
                <Input dir="ltr" className="font-sans text-left flex-1" placeholder="#FF5733"
                  value={newVal.colorHex} onChange={e => setNewVal(p => ({ ...p, colorHex: e.target.value }))} />
              </div>
            </div>
          )}
          <div className="flex gap-3">
            <Button variant="outline" className="flex-1" onClick={() => setAddingValueTo(null)}>انصراف</Button>
            <Button className="flex-1 bg-indigo-600 hover:bg-indigo-700" onClick={() => addingValueTo && handleAddValue(addingValueTo)}>افزودن</Button>
          </div>
        </div>
      </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>
  );
}
