"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 { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { ResponsiveModal } from "@/components/ui/responsive-modal";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
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 { toast } from "sonner";
import { Plus, Edit, Trash2, Award, Search, Globe, Image as ImageIcon, Check, ChevronsUpDown } from "lucide-react";
import { createBrand, updateBrand, deleteBrand, createCountry } from "@/app/actions/brand";
import { Editor } from "@/components/blocks/editor-x/editor";
import MediaManager from "@/components/media/media-manager";
import { TagsInput } from "@/components/ui/tags-input";

export default function BrandsClient({ initialData, initialCountries }: { initialData: any[], initialCountries: any[] }) {
  const [brands, setBrands] = useState(initialData);
  const [countries, setCountries] = useState(initialCountries);
  
  const [search, setSearch] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [isCountryOpen, setIsCountryOpen] = useState(false);
  const [isMediaOpen, setIsMediaOpen] = useState(false);
  const [isCountryMediaOpen, setIsCountryMediaOpen] = useState(false);
  
  const [editing, setEditing] = useState<any>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  
  const [form, setForm] = useState({ name: "", description: "", slug: "", countryId: "", websiteUrl: "", mediaId: "", mediaUrl: "", seoTitle: "", seoDescription: "", seoKeywords: "" });
  const [countryForm, setCountryForm] = useState({ name: "", englishName: "", mediaId: "", mediaUrl: "" });

  const filtered = brands.filter(b => !search || b.name.includes(search) || b.slug?.includes(search));

  const openAdd = () => { 
    setEditing(null); 
    setForm({ 
      name: "", slug: "", description: "", 
      websiteUrl: "", seoTitle: "", seoDescription: "", seoKeywords: "", 
      countryId: "", mediaId: "", mediaUrl: "" 
    }); 
    setIsOpen(true); 
  };
  
  const openEdit = (b: any) => { 
    setEditing(b); 
    setForm({ 
      name: b.name, 
      slug: b.slug || "", 
      description: b.description || "",
      websiteUrl: b.websiteUrl || "",
      seoTitle: b.seoTitle || "",
      seoDescription: b.seoDescription || "",
      seoKeywords: b.seoKeywords || "",
      countryId: b.countryId || "",
      mediaId: b.logoMediaId || "",
      mediaUrl: b.logoMedia?.url || ""
    }); 
    setIsOpen(true); 
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name) return toast.error("نام برند الزامی است.");
    if (!form.countryId) return toast.error("انتخاب کشور سازنده الزامی است.");
    
    if (editing) {
      const res = await updateBrand(editing.id, form);
      if (res.success) { 
        setBrands(p => p.map(b => b.id === editing.id ? res.brand : b)); 
        toast.success("برند ویرایش شد."); 
        setIsOpen(false); 
      }
      else toast.error(res.error);
    } else {
      const res = await createBrand(form);
      if (res.success && res.brand) { 
        setBrands(p => [...p, res.brand]); 
        toast.success("برند ایجاد شد."); 
        setIsOpen(false); 
      }
      else toast.error(res.error);
    }
  };

  const handleCountrySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!countryForm.name) return toast.error("نام کشور الزامی است.");
    const res = await createCountry({ name: countryForm.name, mediaId: countryForm.mediaId });
    if (res.success && res.country) {
      // Refresh countries
      const updatedCountry = { ...res.country, media: res.country.flagMediaId ? { id: res.country.flagMediaId } : null };
      setCountries(p => [...p, updatedCountry]);
      setForm(p => ({ ...p, countryId: res.country.id }));
      toast.success("کشور سازنده اضافه شد.");
      setIsCountryOpen(false);
      setCountryForm({ name: "", englishName: "", mediaId: "", mediaUrl: "" });
    } else {
      toast.error(res.error);
    }
  };

  const handleDelete = async (id: string) => {
    const res = await deleteBrand(id);
    if (res.success) { setBrands(p => p.filter(b => b.id !== id)); toast.success("برند حذف شد."); }
    else toast.error(res.error || "این برند دارای محصول است.");
    setDeleteId(null);
  };

  return (
    <div className="flex flex-col h-full" dir="rtl">
      <PageHeader
        title="مدیریت برندها"
        subtitle={`${brands.length} برند ثبت شده`}
        icon={<Award 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-4">
        {/* Search */}
        <div className="relative max-w-md">
          <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={search} onChange={e => setSearch(e.target.value)} />
        </div>

        {/* Brands Grid */}
        {filtered.length === 0 ? (
          <div className="border-2 border-dashed rounded-xl py-16 text-center text-muted-foreground">
            <Award className="w-10 h-10 mx-auto mb-3 opacity-20" />
            <p>برندی یافت نشد.</p>
            <Button variant="outline" className="mt-4" onClick={openAdd}>ایجاد اولین برند</Button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {filtered.map(brand => (
              <div key={brand.id} className="bg-card border rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow group relative overflow-hidden">
                <div className="flex items-start justify-between mb-3">
                  <div className="w-14 h-14 bg-gradient-to-br from-indigo-100 to-indigo-200 dark:from-indigo-900/30 dark:to-indigo-800/30 rounded-xl flex items-center justify-center text-indigo-600 font-black text-2xl overflow-hidden border">
                    {brand.logoMedia ? (
                       <img src={brand.logoMedia.url} alt={brand.name} className="w-full h-full object-contain bg-white" />
                    ) : (
                       brand.name.charAt(0)
                    )}
                  </div>
                  <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button variant="ghost" size="icon" className="h-8 w-8 bg-background/50 backdrop-blur-sm" onClick={() => openEdit(brand)}><Edit className="w-4 h-4" /></Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-rose-500 bg-background/50 backdrop-blur-sm" onClick={() => setDeleteId(brand.id)}><Trash2 className="w-4 h-4" /></Button>
                  </div>
                </div>
                
                <div className="flex items-center gap-2">
                  <h3 className="font-bold text-lg truncate">{brand.name}</h3>
                  {brand.country && (
                     <div className="flex items-center" title={brand.country.name}>
                       {brand.country.media ? (
                          <img src={brand.country.media.url} alt={brand.country.name} className="w-4 h-3 object-cover rounded-[2px]" />
                       ) : (
                          <span className="text-[10px] bg-muted px-1 rounded">{brand.country.name}</span>
                       )}
                     </div>
                  )}
                </div>
                
                {brand.slug && <p className="text-xs text-muted-foreground font-sans mt-0.5 truncate">{brand.slug}</p>}
                
                {brand.websiteUrl && (
                  <a href={brand.websiteUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs text-indigo-600 hover:underline mt-2">
                    <Globe className="w-3 h-3" />
                    <span className="truncate font-sans max-w-[150px]">{brand.websiteUrl.replace(/^https?:\/\//, '')}</span>
                  </a>
                )}
                
                <div className="mt-3 pt-3 border-t flex items-center justify-between">
                  <Badge variant="secondary" className="text-xs font-sans">
                    {brand._count?.products || 0} محصول
                  </Badge>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${brand.isActive !== false ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400" : "bg-muted text-muted-foreground"}`}>
                    {brand.isActive !== false ? "فعال" : "غیرفعال"}
                  </span>
                </div>
                
                <div className="text-[10px] text-muted-foreground border-t pt-2 mt-3 flex flex-col gap-1">
                  <div className="flex justify-between">
                    <span>ثبت:</span>
                    <span className="font-sans" dir="ltr">{brand.createdBy ? (brand.createdBy.fullName || brand.createdBy.phone) : "سیستم"} - {new Date(brand.createdAt).toLocaleDateString("fa-IR")}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>ویرایش:</span>
                    <span className="font-sans" dir="ltr">{brand.updatedBy ? (brand.updatedBy.fullName || brand.updatedBy.phone) : "سیستم"} - {new Date(brand.updatedAt).toLocaleDateString("fa-IR")}</span>
                  </div>
                </div>
                
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Brand Form Modal */}
      <ResponsiveModal open={isOpen} onOpenChange={setIsOpen} title={editing ? "ویرایش برند" : "برند جدید"}>
        <form onSubmit={handleSubmit} className="p-4 space-y-6 max-h-[85vh] overflow-y-auto">
          
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 space-y-2">
              <Label>نام برند *</Label>
              <Input value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} placeholder="مثال: سامسونگ" required />
            </div>
            <div className="flex-1 space-y-2">
              <Label>لینک سایت اصلی</Label>
              <Input dir="ltr" className="text-left font-sans" value={form.websiteUrl} onChange={e => setForm(p => ({ ...p, websiteUrl: e.target.value }))} placeholder="https://samsung.com" />
            </div>
          </div>

          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 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="samsung" />
            </div>
            <div className="flex-1 space-y-2">
              <div className="flex items-center justify-between">
                <Label>کشور سازنده *</Label>
                <Button type="button" variant="link" size="sm" className="h-auto p-0 text-xs" onClick={() => setIsCountryOpen(true)}>+ کشور جدید</Button>
              </div>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" role="combobox" className={cn("w-full justify-between", !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-[300px] p-0" dir="rtl">
                  <Command>
                    <CommandInput placeholder="جستجوی کشور..." />
                    <CommandList>
                      <CommandEmpty>کشوری یافت نشد.</CommandEmpty>
                      <CommandGroup>
                        {countries.map(c => (
                          <CommandItem key={c.id} value={c.name} onSelect={() => setForm(p => ({ ...p, 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>

          <div className="space-y-2">
            <Label>تصویر برند</Label>
            <div className="flex items-center gap-3">
              <MediaManager 
                mode="single" 
                title="انتخاب تصویر برند" 
                value={form.mediaUrl ? { url: form.mediaUrl, id: form.mediaId } : null}
                open={isMediaOpen}
                onOpenChange={setIsMediaOpen}
                trigger={<Button type="button" variant="outline" className="flex-1 min-w-0 justify-start text-muted-foreground"><ImageIcon className="w-4 h-4 ml-2 shrink-0" /> <span className="truncate">انتخاب تصویر از رسانه...</span></Button>}
                onChange={(m: any) => { setForm(p => ({ ...p, mediaId: m?.id || "", mediaUrl: m?.url || "" })); setIsMediaOpen(false); }}
              />
              {form.mediaUrl && <img src={form.mediaUrl} alt="brand" className="w-10 h-10 shrink-0 object-contain rounded border bg-white" />}
              {form.mediaId && !form.mediaUrl && <span className="text-xs text-emerald-600 bg-emerald-100 px-2 py-1 rounded shrink-0">انتخاب شد</span>}
            </div>
          </div>

          <div className="space-y-2">
            <Label>توضیحات برند</Label>
            <div className="border rounded-lg bg-background">
              <Editor 
                initialHtml={form.description} 
                onHtmlChange={html => setForm(p => ({ ...p, description: html }))} 
              />
            </div>
          </div>

          <div className="space-y-3 p-4 bg-muted/30 rounded-xl border">
            <h4 className="font-semibold text-sm">تنظیمات سئو (SEO)</h4>
            <div className="space-y-2">
              <Label>عنوان سئو (Meta Title)</Label>
              <Input value={form.seoTitle} onChange={e => setForm(p => ({ ...p, seoTitle: e.target.value }))} placeholder="عنوان برای موتورهای جستجو..." />
            </div>
            <div className="space-y-2">
              <Label>کلمات کلیدی سئو</Label>
              <TagsInput value={form.seoKeywords} onChange={v => setForm(p => ({ ...p, seoKeywords: v }))} placeholder="کلمه را وارد کرده و Enter بزنید" />
            </div>
            <div className="space-y-2">
              <Label>توضیحات سئو (Meta Description)</Label>
              <Textarea rows={2} value={form.seoDescription} onChange={e => setForm(p => ({ ...p, seoDescription: e.target.value }))} placeholder="توضیحات متا برای نمایش در نتایج گوگل..." />
            </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>

      {/* Country Form Modal */}
      <ResponsiveModal open={isCountryOpen} onOpenChange={setIsCountryOpen} title="افزودن کشور جدید">
        <form onSubmit={handleCountrySubmit} className="p-4 space-y-4">
          <div className="space-y-2">
            <Label>نام کشور (فارسی) *</Label>
            <Input value={countryForm.name} onChange={e => setCountryForm(p => ({ ...p, name: e.target.value }))} placeholder="مثال: کره جنوبی" required />
          </div>
          <div className="space-y-2">
            <Label>تصویر پرچم</Label>
            <div className="flex items-center gap-3">
              <MediaManager 
                  mode="single" 
                  title="انتخاب پرچم کشور" 
                  open={isCountryMediaOpen}
                  onOpenChange={setIsCountryMediaOpen}
                  trigger={<Button type="button" variant="outline" className="flex-1 justify-start text-muted-foreground"><ImageIcon className="w-4 h-4 ml-2" /> انتخاب از رسانه...</Button>}
                  onChange={(m: any) => { setCountryForm(p => ({ ...p, mediaId: m?.id || "", mediaUrl: m?.url || "" })); setIsCountryMediaOpen(false); }}
                />
              {countryForm.mediaUrl && <img src={countryForm.mediaUrl} alt="flag" className="w-10 h-8 object-cover rounded border" />}
              {countryForm.mediaId && !countryForm.mediaUrl && <span className="text-xs text-emerald-600 bg-emerald-100 px-2 py-1 rounded">پرچم انتخاب شد</span>}
            </div>
          </div>
          <div className="flex gap-3 pt-2">
            <Button type="button" variant="outline" className="flex-1" onClick={() => setIsCountryOpen(false)}>انصراف</Button>
            <Button type="submit" className="flex-1 bg-emerald-600 hover:bg-emerald-700">ثبت کشور</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>
  );
}
