"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { cn } from "@/lib/utils";
import {
  Store, DollarSign, Box, Image as ImageIcon, Bot, Sliders, Save, X, Plus, Star, Check, ChevronsUpDown, TrendingUp, AlertCircle
} from "lucide-react";
import { createProduct, updateProduct } from "@/app/actions/product";
import MediaManager, { MediaPicked } from "@/components/media/media-manager";
import { RichTextEditor } from "@/components/rich-text-editor";
import { PageHeader } from "@/components/page-header";
import {
  InlineBrandSelect,
  InlineCategorySelect,
  VariantManager, CustomAttributesEditor, SeoPreview,
  type Variant, type CustomAttr, type AttributeValueObj
} from "./product-form-parts";
import { TagsInput } from "@/components/ui/tags-input";
import { ProductAnalyticsTab } from "./product-analytics-tab";

interface ProductFormProps {
  categories: any[];
  media: any[];
  brands: any[];
  countries: any[];
  attributes: any[];
  product?: any;
}

export function ProductForm({ categories, media, brands, countries, attributes, product }: ProductFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [images, setImages] = useState<string[]>(product?.images?.map((i: any) => i.imageUrl) || []);
  const [selectedCategories, setSelectedCategories] = useState<string[]>(
    product?.categories?.map((c: any) => c.categoryId) || []
  );
  const [variants, setVariants] = useState<Variant[]>(() => {
    if (!product?.variants) return [];
    return product.variants.map((v: any) => {
      const options: any = {};
      v.options?.forEach((opt: any) => {
        options[opt.attribute.name] = opt.value;
      });
      return {
        id: v.id,
        options,
        sku: v.sku || "",
        price: v.price?.toString() || "",
        stock: v.stockQuantity?.toString() || "",
        image: v.featuredMediaId || "",
        active: v.isActive,
      };
    });
  });

  const [attributeGroups, setAttributeGroups] = useState<{ name: string; values: AttributeValueObj[] }[]>(() => {
    if (!product?.variants) return [];
    const groupsMap = new Map<string, Set<string>>();
    product.variants.forEach((v: any) => {
      v.options?.forEach((opt: any) => {
        if (!groupsMap.has(opt.attribute.name)) groupsMap.set(opt.attribute.name, new Set());
        groupsMap.get(opt.attribute.name)!.add(opt.value);
      });
    });
    return Array.from(groupsMap.entries()).map(([name, values]) => ({
      name,
      values: Array.from(values).map(v => ({ name: v, imageUrl: "" }))
    }));
  });

  const [customAttrs, setCustomAttrs] = useState<CustomAttr[]>(() => {
    if (!product?.productAttributes) return [];
    return product.productAttributes.map((pa: any) => ({
      name: pa.attribute.name,
      value: pa.value
    }));
  });

  const [form, setForm] = useState({
    title: product?.title || "",
    titleEn: product?.titleEn || "",
    slug: product?.slug || "",
    shortDescription: product?.shortDesc || "",
    description: product?.description || "",
    status: product?.status || "PUBLISHED",
    isFeatured: product?.isFeatured || false,
    basePrice: product?.price?.toString() || "0",
    usdPrice: "",
    discountPrice: product?.salePrice?.toString() || "",
    manageStock: product?.manageStock || false,
    stock: product?.stockQuantity?.toString() || "0",
    lowStockThreshold: product?.lowStockThreshold?.toString() || "5",
    sku: product?.sku || "",
    barcode: product?.barcode || "",
    weightGrams: product?.weightGrams?.toString() || "",
    lengthMm: product?.lengthMm?.toString() || "",
    widthMm: product?.widthMm?.toString() || "",
    heightMm: product?.heightMm?.toString() || "",
    brandId: product?.brandId || "",
    countryId: product?.countryId || "",
    seoTitle: product?.seoTitle || "",
    seoDescription: product?.seoDescription || "",
    seoKeywords: product?.seoKeywords || "",
    aiSummary: "",
  });

  const set = (k: string, v: any) => setForm((p) => ({ ...p, [k]: v }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.title) return toast.error("نام محصول الزامی است.");
    if (!form.countryId) return toast.error("انتخاب کشور سازنده الزامی است.");
    setLoading(true);
    try {
      const payload = {
        ...form,
        basePrice: parseInt(form.basePrice) || 0,
        discountPrice: form.discountPrice ? parseInt(form.discountPrice) : null,
        stock: parseInt(form.stock) || 0,
        lowStockThreshold: parseInt(form.lowStockThreshold) || 5,
        weightGrams: form.weightGrams ? parseInt(form.weightGrams) : null,
        lengthMm: form.lengthMm ? parseInt(form.lengthMm) : null,
        widthMm: form.widthMm ? parseInt(form.widthMm) : null,
        heightMm: form.heightMm ? parseInt(form.heightMm) : null,
        categoryIds: selectedCategories,
        imageUrls: images,
        brandId: form.brandId || null,
        countryId: form.countryId || null,
        variants,
        customAttributes: customAttrs,
      };
      const res = product ? await updateProduct(product.id, payload) : await createProduct(payload);
      if (res.success) {
        toast.success(product ? "محصول ویرایش شد." : "محصول ذخیره شد.");
        router.push("/admin/products");
      } else toast.error(res.error || "خطا");
    } catch { toast.error("خطای شبکه"); }
    finally { setLoading(false); }
  };

  const removeImage = (url: string) => setImages((p) => p.filter((i) => i !== url));

  const handleMediaManagerChange = (picked: MediaPicked | MediaPicked[] | null) => {
    if (!picked) return;
    const items = Array.isArray(picked) ? picked : [picked];
    setImages((prev) => {
        const newUrls = items.map(i => i.url);
        // union
        return Array.from(new Set([...prev, ...newUrls]));
    });
  };

  return (
    <>
      <PageHeader
        title={product ? `ویرایش: ${product.title}` : "افزودن محصول جدید"}
        subtitle="فرم پیشرفته مدیریت محصول با واریانت و آتریبوت"
        icon={<Store className="w-4 h-4" />}
        actions={[
          { label: "انصراف", icon: <X className="w-4 h-4" />, onClick: () => router.push("/admin/products"), variant: "outline" },
          { label: form.status === "DRAFT" ? "ذخیره پیش‌نویس" : "انتشار محصول", icon: <Save className="w-4 h-4" />, onClick: () => document.getElementById("product-form-submit")?.click(), variant: "default", className: form.status === "DRAFT" ? "bg-amber-600 hover:bg-amber-700 text-white" : "bg-indigo-600 hover:bg-indigo-700 text-white" },
        ]}
      />

      <form id="product-form" onSubmit={handleSubmit} className="flex flex-col lg:flex-row gap-4 p-4 md:p-5 max-w-7xl mx-auto w-full">
        <button id="product-form-submit" type="submit" className="hidden" />

        {/* Main Tabs */}
        <div className="flex-1 min-w-0">
          <Tabs defaultValue="general">
            <TabsList className="w-full bg-card border rounded-xl h-auto p-1 flex-wrap gap-1">
              {[
                { value: "general", icon: <Store className="w-3.5 h-3.5" />, label: "اطلاعات" },
                { value: "pricing", icon: <DollarSign className="w-3.5 h-3.5" />, label: "قیمت" },
                { value: "stock", icon: <Box className="w-3.5 h-3.5" />, label: "انبار" },
                { value: "variants", icon: <Sliders className="w-3.5 h-3.5" />, label: "واریانت‌ها" },
                { value: "attrs", icon: <Sliders className="w-3.5 h-3.5" />, label: "مشخصات" },
                { value: "media", icon: <ImageIcon className="w-3.5 h-3.5" />, label: "رسانه" },
                { value: "seo", icon: <Bot className="w-3.5 h-3.5 text-purple-500" />, label: "سئو+AI" },
                ...(product ? [{ value: "analytics", icon: <TrendingUp className="w-3.5 h-3.5 text-emerald-500" />, label: "آمار و انبار" }] : []),
              ].map((t) => (
                <TabsTrigger key={t.value} value={t.value} className="gap-1 py-1.5 px-2.5 text-xs whitespace-nowrap">
                  {t.icon} {t.label}
                </TabsTrigger>
              ))}
            </TabsList>

            <div className="mt-4 space-y-4">
              {/* GENERAL */}
              <TabsContent value="general">
                <Card><CardContent className="p-5 space-y-4">
                  <div className="space-y-2">
                    <Label className="font-semibold">نام محصول <span className="text-red-500">*</span></Label>
                    <Input value={form.title} onChange={(e) => set("title", e.target.value)} placeholder="مثال: گوشی سامسونگ A55" className="text-base" />
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label className="font-semibold">نام انگلیسی</Label>
                      <Input dir="ltr" className="text-left font-sans" value={form.titleEn} onChange={(e) => set("titleEn", e.target.value)} placeholder="Samsung Galaxy A55" />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">Slug</Label>
                      <Input dir="ltr" className="text-left font-sans" value={form.slug} onChange={(e) => set("slug", e.target.value)} placeholder="samsung-galaxy-a55" />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label className="font-semibold">توضیح کوتاه</Label>
                    <RichTextEditor value={form.shortDescription} onChange={(v) => set("shortDescription", v)} placeholder="ویژگی‌های کلیدی محصول..." />
                  </div>
                  <div className="space-y-2">
                    <Label className="font-semibold">توضیحات کامل</Label>
                    <RichTextEditor value={form.description} onChange={(v) => set("description", v)} placeholder="بررسی تخصصی و مشخصات کامل..." />
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label className="font-semibold">برند</Label>
                      <InlineBrandSelect brands={brands} countries={countries} value={form.brandId} onChange={(v, brand) => {
                        set("brandId", v);
                        if (brand?.countryId) set("countryId", brand.countryId);
                      }} />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">کشور سازنده *</Label>
                      <Popover>
                        <PopoverTrigger asChild>
                          <Button variant="outline" role="combobox" className={cn("w-full justify-between font-normal", !form.countryId && "text-muted-foreground")}>
                            {form.countryId ? (
                              <div className="flex items-center gap-2">
                                {countries.find(c => c.id === form.countryId)?.media && (
                                  <img src={countries.find(c => c.id === form.countryId)?.media?.url} alt="" className="w-5 h-4 object-cover rounded-sm" />
                                )}
                                <span>{countries.find(c => c.id === form.countryId)?.name}</span>
                              </div>
                            ) : "انتخاب کشور..."}
                            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent className="w-full min-w-[300px] p-0" dir="rtl">
                          <Command>
                            <CommandInput placeholder="جستجوی کشور..." />
                            <CommandList>
                              <CommandEmpty>کشوری یافت نشد.</CommandEmpty>
                              <CommandGroup>
                                {countries.map(c => (
                                  <CommandItem key={c.id} value={c.name} onSelect={() => set("countryId", c.id)}>
                                    <Check className={cn("mr-2 h-4 w-4", form.countryId === c.id ? "opacity-100" : "opacity-0")} />
                                    <div className="flex items-center gap-2 mr-2">
                                       {c.media && <img src={c.media.url} alt="" className="w-5 h-4 object-cover rounded-sm" />}
                                       <span>{c.name}</span>
                                    </div>
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">وضعیت</Label>
                      <Select value={form.status} onValueChange={(v) => set("status", v)}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          <SelectItem value="PUBLISHED">منتشر شده</SelectItem>
                          <SelectItem value="DRAFT">پیش‌نویس</SelectItem>
                          <SelectItem value="HIDDEN">مخفی</SelectItem>
                          <SelectItem value="ARCHIVED">آرشیو</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label className="font-semibold">دسته‌بندی‌ها</Label>
                    <div className="border rounded-xl p-3 bg-muted/5 max-h-80 overflow-y-auto">
                        <InlineCategorySelect categories={categories} value={selectedCategories} onChange={setSelectedCategories} />
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 bg-amber-50 dark:bg-amber-900/10 rounded-xl border border-amber-100 dark:border-amber-900/30">
                    <Star className="w-4 h-4 text-amber-500" />
                    <Label className="font-semibold flex-1">محصول ویژه (Featured)</Label>
                    <Switch checked={form.isFeatured} onCheckedChange={(v) => set("isFeatured", v)} />
                  </div>
                </CardContent></Card>
              </TabsContent>

              {/* PRICING */}
              <TabsContent value="pricing">
                <Card><CardContent className="p-5 space-y-4">
                  <div className="p-4 bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-900/30 rounded-xl">
                    <p className="text-sm font-bold text-blue-800 dark:text-blue-300 flex items-center gap-2"><DollarSign className="w-4 h-4" /> قیمت‌گذاری هوشمند ارزی</p>
                    <p className="text-xs text-blue-600 mt-1">با ثبت قیمت دلاری، از تنظیمات می‌توانید همه قیمت‌ها را با نرخ روز بروزرسانی کنید.</p>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label className="font-semibold text-blue-700">قیمت ارزی (دلار)</Label>
                      <div className="relative"><DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-blue-500" /><Input dir="ltr" className="pl-9 font-sans text-left" placeholder="0.00" value={form.usdPrice} onChange={(e) => set("usdPrice", e.target.value)} /></div>
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">قیمت اصلی (تومان) <span className="text-red-500">*</span></Label>
                      <Input dir="ltr" className="font-sans text-left" value={form.basePrice} onChange={(e) => set("basePrice", e.target.value)} />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">قیمت با تخفیف (تومان)</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="خالی = بدون تخفیف" value={form.discountPrice} onChange={(e) => set("discountPrice", e.target.value)} />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">وزن (گرم)</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="500" value={form.weightGrams} onChange={(e) => set("weightGrams", e.target.value)} />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">طول (میلی‌متر)</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="100" value={form.lengthMm} onChange={(e) => set("lengthMm", e.target.value)} />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">عرض (میلی‌متر)</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="100" value={form.widthMm} onChange={(e) => set("widthMm", e.target.value)} />
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">ارتفاع (میلی‌متر)</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="100" value={form.heightMm} onChange={(e) => set("heightMm", e.target.value)} />
                    </div>
                  </div>
                </CardContent></Card>
              </TabsContent>

              {/* STOCK */}
              <TabsContent value="stock">
                <Card><CardContent className="p-5 space-y-4">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label className="font-semibold">کد SKU</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="SKU-001" value={form.sku} onChange={(e) => set("sku", e.target.value)} />
                      <p className="text-xs text-muted-foreground">توسط بارکدخوان در POS اسکن می‌شود.</p>
                    </div>
                    <div className="space-y-2">
                      <Label className="font-semibold">بارکد فیزیکی</Label>
                      <Input dir="ltr" className="font-sans text-left" placeholder="6260..." value={form.barcode} onChange={(e) => set("barcode", e.target.value)} />
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 bg-muted/30 rounded-xl border">
                    <Box className="w-4 h-4 text-indigo-500" />
                    <Label className="font-semibold flex-1">مدیریت موجودی انبار</Label>
                    <Switch checked={form.manageStock} onCheckedChange={(v) => set("manageStock", v)} />
                  </div>
                  {form.manageStock && (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label className="font-semibold">موجودی فعلی</Label>
                        <Input type="number" dir="ltr" className="font-sans text-left" value={form.stock} onChange={(e) => set("stock", e.target.value)} />
                      </div>
                      <div className="space-y-2">
                        <Label className="font-semibold">آستانه هشدار</Label>
                        <Input type="number" dir="ltr" className="font-sans text-left" value={form.lowStockThreshold} onChange={(e) => set("lowStockThreshold", e.target.value)} />
                      </div>
                    </div>
                  )}
                </CardContent></Card>
              </TabsContent>

              {/* VARIANTS */}
              <TabsContent value="variants">
                <Card><CardContent className="p-5">
                  <VariantManager
                    globalAttributes={attributes}
                    variants={variants} onChange={setVariants}
                    attributeGroups={attributeGroups} onGroupsChange={setAttributeGroups}
                  />
                </CardContent></Card>
              </TabsContent>

              {/* CUSTOM ATTRS */}
              <TabsContent value="attrs">
                <Card><CardContent className="p-5 space-y-4">
                  <div>
                    <p className="font-bold mb-1">مشخصات فنی / آتریبوت‌های سفارشی</p>
                    <p className="text-xs text-muted-foreground">مثلاً: کشور سازنده، جنس، ابعاد، گارانتی...</p>
                  </div>
                  <CustomAttributesEditor globalAttributes={attributes} attrs={customAttrs} onChange={setCustomAttrs} />
                </CardContent></Card>
              </TabsContent>

              {/* MEDIA */}
              <TabsContent value="media">
                <Card><CardContent className="p-5 space-y-4">
                  <div className="space-y-4">
                    <MediaManager 
                        mode="multiple" 
                        onChange={handleMediaManagerChange} 
                        triggerLabel="افزودن تصویر جدید" 
                        triggerClassName="w-full h-24 border-dashed rounded-xl bg-muted/20 hover:bg-muted/50 transition-colors"
                    />
                    <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 mt-4">
                      {images.map((url, i) => (
                      <div key={url} className="relative aspect-square rounded-xl overflow-hidden border group">
                        <img src={url} alt="" className="w-full h-full object-cover" />
                        {i === 0 && <span className="absolute top-1 right-1 bg-indigo-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded">اصلی</span>}
                        <button type="button" onClick={() => removeImage(url)}
                          className="absolute top-1 left-1 bg-red-500 text-white rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
                          <X className="w-3 h-3" />
                        </button>
                      </div>
                    ))}
                    </div>
                  </div>
                </CardContent></Card>
              </TabsContent>

              {/* SEO */}
              <TabsContent value="seo">
                <Card className="border-purple-100 dark:border-purple-900/30"><CardContent className="p-5 space-y-4">
                  <SeoPreview title={form.seoTitle || form.title} description={form.seoDescription} slug={form.slug} />
                  <div className="space-y-2">
                    <Label className="font-semibold">عنوان سئو</Label>
                    <Input value={form.seoTitle} onChange={(e) => set("seoTitle", e.target.value)} placeholder="حداکثر ۶۰ کاراکتر" />
                  </div>
                  <div className="space-y-2">
                    <Label className="font-semibold">توضیحات متا</Label>
                    <Input value={form.seoDescription} onChange={(e) => set("seoDescription", e.target.value)} placeholder="حداکثر ۱۶۰ کاراکتر" />
                  </div>
                  <div className="space-y-2">
                    <Label className="font-semibold">کلمات کلیدی</Label>
                    <TagsInput value={form.seoKeywords} onChange={(v) => set("seoKeywords", v)} placeholder="کلمه را تایپ کنید و Enter بزنید" />
                  </div>
                  <div className="space-y-2 border-t pt-4">
                    <Label className="font-semibold text-purple-700 flex items-center gap-2"><Bot className="w-4 h-4" /> متن سمانتیک AI</Label>
                    <textarea rows={4} className="w-full border rounded-xl px-3 py-2 text-sm bg-background resize-none focus:outline-none focus:ring-2 focus:ring-purple-300" value={form.aiSummary} onChange={(e) => set("aiSummary", e.target.value)} placeholder="خلاصه ساختاریافته برای ChatGPT Search، Perplexity و Gemini..." />
                    <p className="text-xs text-muted-foreground">در JSON-LD (Schema.org) جاسازی می‌شود.</p>
                  </div>
                </CardContent></Card>
              </TabsContent>
              {/* ANALYTICS (ONLY IN EDIT) */}
              {product && (
                <TabsContent value="analytics">
                  <ProductAnalyticsTab productId={product.id} />
                </TabsContent>
              )}
            </div>
          </Tabs>
        </div>

        {/* Sidebar Summary */}
        <div className="w-full lg:w-64 shrink-0">
          <Card className="sticky top-20 shadow-md border-indigo-100 dark:border-indigo-900/30 overflow-hidden">
            <div className="bg-gradient-to-r from-indigo-500 to-purple-600 h-2 w-full"></div>
            <CardContent className="p-4 space-y-5">
              <h3 className="font-black text-lg text-indigo-950 dark:text-indigo-100 flex items-center gap-2">
                <Store className="w-4 h-4 text-indigo-500" /> خلاصه محصول
              </h3>
              
              {/* Pricing Summary */}
              <div className="bg-muted/40 rounded-xl p-3 border border-border/50">
                <p className="text-xs text-muted-foreground mb-1">قیمت نهایی برای مشتری</p>
                <div className="flex items-center justify-between">
                  <span className="font-black text-lg text-indigo-700 dark:text-indigo-400 font-sans">
                    {(parseInt(form.discountPrice) || parseInt(form.basePrice) || 0).toLocaleString("fa-IR")}
                  </span>
                  <span className="text-xs">تومان</span>
                </div>
                {form.discountPrice && parseInt(form.discountPrice) < parseInt(form.basePrice) && (
                  <div className="flex items-center gap-1 mt-1 text-xs text-rose-500">
                    <TrendingUp className="w-3 h-3" />
                    <span>{Math.round(((parseInt(form.basePrice) - parseInt(form.discountPrice)) / parseInt(form.basePrice)) * 100).toLocaleString("fa-IR")}% تخفیف</span>
                  </div>
                )}
              </div>

              {/* Stock Status */}
              <div className={cn(
                "rounded-xl p-3 border flex items-start gap-2",
                form.manageStock 
                  ? parseInt(form.stock) <= parseInt(form.lowStockThreshold)
                    ? parseInt(form.stock) <= 0
                      ? "bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-900/20 dark:border-rose-800/50" // Out of stock
                      : "bg-amber-50 border-amber-200 text-amber-700 dark:bg-amber-900/20 dark:border-amber-800/50" // Low stock
                    : "bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-900/20 dark:border-emerald-800/50" // In stock
                  : "bg-slate-50 border-slate-200 text-slate-700 dark:bg-slate-900/20 dark:border-slate-800/50" // Always available
              )}>
                {form.manageStock && parseInt(form.stock) <= 0 ? (
                  <AlertCircle className="w-4 h-4 mt-0.5 shrink-0" />
                ) : (
                  <Box className="w-4 h-4 mt-0.5 shrink-0" />
                )}
                <div className="flex-1">
                  <p className="text-xs font-bold leading-none mb-1">وضعیت انبار</p>
                  <p className="text-xs font-sans">
                    {!form.manageStock ? "نامحدود (بدون مدیریت موجودی)" : 
                     parseInt(form.stock) <= 0 ? "ناموجود" : 
                     `${parseInt(form.stock).toLocaleString("fa-IR")} عدد موجود`}
                  </p>
                </div>
              </div>

              {/* Stats Grid */}
              <div className="grid grid-cols-2 gap-2 text-xs">
                  <div className="bg-muted/30 rounded-lg p-2 text-center border border-border/50">
                    <p className="text-muted-foreground mb-1">تصاویر</p>
                    <p className="font-bold font-sans">{images.length}</p>
                  </div>
                  <div className="bg-muted/30 rounded-lg p-2 text-center border border-border/50">
                    <p className="text-muted-foreground mb-1">واریانت‌ها</p>
                    <p className="font-bold font-sans">{variants.length}</p>
                  </div>
                  <div className="bg-muted/30 rounded-lg p-2 text-center border border-border/50">
                    <p className="text-muted-foreground mb-1">دسته‌ها</p>
                    <p className="font-bold font-sans">{selectedCategories.length}</p>
                  </div>
                  <div className="bg-muted/30 rounded-lg p-2 text-center border border-border/50">
                    <p className="text-muted-foreground mb-1">مشخصات</p>
                    <p className="font-bold font-sans">{customAttrs.length}</p>
                  </div>
              </div>

              <div className="space-y-2 pt-2 border-t">
                <Button type="submit" form="product-form" disabled={loading} className="w-full bg-indigo-600 hover:bg-indigo-700 gap-2 h-10 text-sm font-bold shadow-md shadow-indigo-200 dark:shadow-none transition-all hover:scale-[1.02]">
                  <Save className="w-4 h-4" /> {loading ? "در حال ذخیره..." : "ذخیره تغییرات"}
                </Button>
                <Button type="button" variant="ghost" className="w-full text-xs" onClick={() => router.push("/admin/products")}>انصراف و بازگشت</Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </form>
    </>
  );
}
