"use client";

import { useState, useRef, useEffect } from "react";
import { useSidebar } from "@/components/ui/sidebar";
import { PageHeader } from "@/components/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { SettingsIcon, ShieldAlert, DatabaseIcon, DownloadCloudIcon, UploadCloudIcon, CloudIcon, DollarSign, RefreshCw, SaveIcon, MessageSquare, Percent, Globe, Printer, Trash2 } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import { ResponsiveActions } from "@/components/ui/responsive-actions";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import MediaManager from "@/components/media/media-manager";
import { ImageIcon, PackageIcon, RefreshCwIcon, DownloadIcon, CheckCircle2 } from "lucide-react";
import { ColorPicker } from "@/components/ui/color-picker";
import { createFullBackup, restoreFromBackup } from "@/app/actions/backup";
import { performPullSync, recoverPhysicalFiles } from "@/app/actions/sync";
import { bulkUpdatePriceByUsdRate } from "@/app/actions/product";
import { updateSettings } from "@/app/actions/settings";
import { format } from "date-fns-jalali";
import { BorderGlow } from "@/components/ui/border-glow";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";

export default function SettingsClient({ initialSettings }: { initialSettings: any }) {
  const { setOpen } = useSidebar();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [updateState, setUpdateState] = useState<{ checking: boolean; result: any | null }>({ checking: false, result: null });
  const [recoveringServer, setRecoveringServer] = useState(false);
  const [showRecoveryConfirm, setShowRecoveryConfirm] = useState(false);
  const [backupsList, setBackupsList] = useState<any[]>([]);
  const [usdRate, setUsdRate] = useState("");
  const [updatingPrices, setUpdatingPrices] = useState(false);
  const [savingSettings, setSavingSettings] = useState(false);
  const [systemPrinters, setSystemPrinters] = useState<{name: string, isDefault: boolean}[]>([]);

  // Settings State
  const [settingsForm, setSettingsForm] = useState({
    siteName: initialSettings?.siteName || "",
    siteDescription: initialSettings?.siteDescription || "",
    phone: initialSettings?.phone || "",
    address: initialSettings?.address || "",
    onlineServerUrl: initialSettings?.onlineServerUrl || "",
    instagramUrl: initialSettings?.instagramUrl || "",
    telegramUrl: initialSettings?.telegramUrl || "",
    whatsappUrl: initialSettings?.whatsappUrl || "",
    logoUrl: initialSettings?.logoUrl || "",
    logoDarkUrl: initialSettings?.logoDarkUrl || "",
    logoLightUrl: initialSettings?.logoLightUrl || "",
    faviconUrl: initialSettings?.faviconUrl || "",
    primaryColor: initialSettings?.primaryColor || "",
    pwaAppName: initialSettings?.pwaAppName || "",
    pwaShortName: initialSettings?.pwaShortName || "",
    pwaThemeColor: initialSettings?.pwaThemeColor || "",
    pwaBgColor: initialSettings?.pwaBgColor || "",
    pwaIconUrl: initialSettings?.pwaIconUrl || "",
    taxEnabled: initialSettings?.taxEnabled ?? false,
    taxRate: initialSettings?.taxRate ?? 10.0,
    reviewsAutoApprove: initialSettings?.reviewsAutoApprove ?? false,
    reviewsAllowMedia: initialSettings?.reviewsAllowMedia ?? true,
    receiptPrinter: JSON.parse(initialSettings?.printers || "{}").receiptPrinter || "",
    labelPrinter: JSON.parse(initialSettings?.printers || "{}").labelPrinter || "",
    socialLinks: initialSettings?.socialLinks ? (typeof initialSettings.socialLinks === 'string' ? JSON.parse(initialSettings.socialLinks) : initialSettings.socialLinks) : [],
  });

  const handleSettingsChange = (field: string, value: any) => {
    setSettingsForm(prev => ({ ...prev, [field]: value }));
  };

  const saveGeneralSettings = async () => {
    setSavingSettings(true);
    const payload = { ...settingsForm };
    const printers = JSON.stringify({ receiptPrinter: payload.receiptPrinter, labelPrinter: payload.labelPrinter });
    const res = await updateSettings(initialSettings.id, { ...payload, printers });
    setSavingSettings(false);
    if (res.success) {
      toast.success("تنظیمات با موفقیت ذخیره شد");
    } else {
      toast.error("خطا در ذخیره تنظیمات: " + res.error);
    }
  };

  const handleBulkPriceUpdate = async () => {
    const rate = parseFloat(usdRate);
    if (!rate || rate <= 0) return toast.error("نرخ دلار معتبر وارد کنید.");
    if (!confirm(`آیا مطمئن هستید؟ قیمت‌ها بر اساس نرخ ${rate.toLocaleString("fa-IR")} تومان/دلار بروزرسانی می‌شوند.`)) return;
    setUpdatingPrices(true);
    const res = await bulkUpdatePriceByUsdRate(rate);
    setUpdatingPrices(false);
    if (res.success) {
      toast.success(`قیمت ${res.updatedCount} محصول با موفقیت بروزرسانی شد!`);
    } else {
      toast.error("خطا در بروزرسانی قیمت‌ها: " + res.error);
    }
  };

  useEffect(() => {
    const fetchBackups = async () => {
      try {
        const { getBackupsList } = await import("@/app/actions/backup");
        const res = await getBackupsList();
        if (res.success) setBackupsList(res.backups || []);
      } catch(e) {}
    };
    fetchBackups();

    const fetchPrinters = async () => {
      try {
        if (typeof window !== "undefined" && (window as any).require) {
          const { ipcRenderer } = (window as any).require("electron");
          const printers = await ipcRenderer.invoke("get-printers");
          setSystemPrinters(printers || []);
        }
      } catch (e) {}
    };
    fetchPrinters();
  }, []);

  const fullServerRecovery = async () => {
    setShowRecoveryConfirm(false);
    setRecoveringServer(true);
    const toastId = toast.loading("در حال دریافت اطلاعات از سرور آنلاین...");
    try {
      await performPullSync(null);
      toast.loading("در حال استخراج و دانلود تصاویر و فایل‌ها...", { id: toastId });
      await recoverPhysicalFiles();
      toast.success("بازگردانی اطلاعات با موفقیت انجام شد!", { id: toastId });
      setTimeout(() => window.location.reload(), 2000);
    } catch (e) {
      toast.error("خطا در بازگردانی اطلاعات سرور", { id: toastId });
    } finally {
      setRecoveringServer(false);
    }
  };

  const handleBackup = async () => {
    const toastId = toast.loading("در حال پردازش هسته و تهیه نسخه پشتیبان...");
    const res = await createFullBackup();
    if (res.success && res.url) {
      toast.success("آرشیو پشتیبان با موفقیت ساخته شد! در حال دانلود...", { id: toastId });
      window.location.href = res.url;
    } else {
      toast.error("خطا در ایجاد پشتیبان: " + res.error, { id: toastId });
    }
  };

  const handleRestore = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!confirm("هشدار بسیار مهم: پیامدهای این عملیات غیرقابل بازگشت است!")) {
      if (fileInputRef.current) fileInputRef.current.value = "";
      return;
    }

    const toastId = toast.loading("در حال استخراج و بازنویسی هسته اطلاعات...");
    const formDataBody = new FormData();
    formDataBody.append("file", file);

    const res = await restoreFromBackup(formDataBody);
    if (res.success) {
      toast.success("بازگردانی با موفقیت انجام شد! ری‌استارت می‌شود.", { id: toastId });
      setTimeout(() => window.location.reload(), 2500);
    } else {
      toast.error("خطای بحرانی: " + res.error, { id: toastId });
    }
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const planType = (initialSettings as any).licensePlan as string | null;
  const planName = (initialSettings as any).licensePlanName as string | null;

  const PLAN_STYLE: Record<string, { gradient: string; border: string; glow: string; icon: string; badge: string; emoji: string; label: string }> = {
    BRONZE:  { gradient: "from-amber-950 via-amber-900 to-stone-900",  border: "border-amber-500/30",  glow: "#b45309", icon: "text-amber-400",  badge: "bg-amber-500/20 text-amber-300 border-amber-500/40", emoji: "🥉", label: "برنز" },
    SILVER:  { gradient: "from-slate-800 via-slate-700 to-slate-900",  border: "border-slate-400/30",  glow: "#64748b", icon: "text-slate-300",  badge: "bg-slate-400/20 text-slate-200 border-slate-400/40", emoji: "🥈", label: "نقره‌ای" },
    DIAMOND: { gradient: "from-blue-950 via-indigo-900 to-slate-900",  border: "border-blue-400/30",   glow: "#3b82f6", icon: "text-blue-300",   badge: "bg-blue-500/20 text-blue-200 border-blue-400/40",   emoji: "💎", label: "الماس" },
    CUSTOM:  { gradient: "from-emerald-950 via-emerald-900 to-slate-900", border: "border-emerald-500/30", glow: "#10b981", icon: "text-emerald-400", badge: "bg-emerald-500/20 text-emerald-200 border-emerald-500/40", emoji: "⚙️", label: "سفارشی" },
  };
  const style = PLAN_STYLE[planType || ""] || { gradient: "from-slate-900 via-indigo-950 to-slate-900", border: "border-indigo-500/20", glow: "#6366f1", icon: "text-indigo-400", badge: "bg-indigo-500/20 text-indigo-200 border-indigo-500/40", emoji: "🔐", label: "نامشخص" };

  return (
    <div className="flex flex-col h-full bg-background text-foreground">
      <PageHeader
        title="تنظیمات"
        subtitle="مدیریت سیستم، پیکربندی آنلاین، بکاپ و لایسنس"
        icon={<SettingsIcon className="w-5 h-5" />}
      >
        <ResponsiveActions actions={[
          { label: savingSettings ? "در حال ذخیره..." : "ذخیره تغییرات", icon: <SaveIcon className="w-4 h-4" />, onClick: saveGeneralSettings, className: "bg-emerald-600 hover:bg-emerald-700 text-white hover:text-white shadow-md" }
        ]} />
      </PageHeader>

      <main className="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 bg-muted/20">
        <div className="max-w-6xl mx-auto">
          
          <Tabs defaultValue="general" className="w-full space-y-6">
            
            <div className="w-full relative z-10">
              <TabsList className="flex flex-wrap h-auto w-full p-1.5 gap-2 bg-transparent">
                <TabsTrigger 
                  value="general" 
                  className="justify-center gap-2 py-2.5 px-4 rounded-xl text-muted-foreground hover:bg-muted/50 data-[state=active]:bg-indigo-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all font-medium text-sm flex-1 sm:flex-none"
                >
                  <SettingsIcon className="w-4 h-4" />
                  عمومی
                </TabsTrigger>
                
                <TabsTrigger 
                  value="sales" 
                  className="justify-center gap-2 py-2.5 px-4 rounded-xl text-muted-foreground hover:bg-muted/50 data-[state=active]:bg-indigo-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all font-medium text-sm flex-1 sm:flex-none"
                >
                  <DollarSign className="w-4 h-4" />
                  مالی، فروش و نظرات
                </TabsTrigger>
                
                <TabsTrigger 
                  value="hardware" 
                  className="justify-center gap-2 py-2.5 px-4 rounded-xl text-muted-foreground hover:bg-muted/50 data-[state=active]:bg-indigo-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all font-medium text-sm flex-1 sm:flex-none"
                >
                  <Printer className="w-4 h-4" />
                  سخت‌افزار و ارتباطات
                </TabsTrigger>
                
                <TabsTrigger 
                  value="system" 
                  className="justify-center gap-2 py-2.5 px-4 rounded-xl text-muted-foreground hover:bg-muted/50 data-[state=active]:bg-indigo-600 data-[state=active]:text-white data-[state=active]:shadow-md transition-all font-medium text-sm flex-1 sm:flex-none"
                >
                  <ShieldAlert className="w-4 h-4" />
                  سیستم و لایسنس
                </TabsTrigger>
              </TabsList>
            </div>

            {/* Content Area */}
            <div className="w-full min-w-0">
              
              {/* General Settings */}
              <TabsContent value="general" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
                <div className="bg-card border rounded-3xl shadow-sm p-6 space-y-6 relative overflow-hidden">
                  <div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/5 rounded-bl-full -z-0"></div>
                  
                  <div className="border-b pb-4 relative z-10">
                    <h2 className="text-xl font-bold flex items-center gap-2">
                      <SettingsIcon className="w-6 h-6 text-indigo-500" /> مشخصات اصلی فروشگاه
                    </h2>
                    <p className="text-sm text-muted-foreground mt-1">اطلاعات هویتی و اصلی وب‌سایت و کسب‌و‌کار شما.</p>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6 relative z-10">
                    <div className="space-y-2">
                      <label className="text-sm font-bold text-muted-foreground">نام فروشگاه/سایت</label>
                      <Input value={settingsForm.siteName} onChange={e => handleSettingsChange("siteName", e.target.value)} placeholder="مثلاً فروشگاه آنلاین توکان" className="bg-muted/20" />
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-bold text-muted-foreground">تلفن تماس فروشگاه</label>
                      <Input dir="ltr" value={settingsForm.phone} onChange={e => handleSettingsChange("phone", e.target.value)} placeholder="021XXXXXXXX" className="bg-muted/20 text-right" />
                    </div>
                    <div className="space-y-2 md:col-span-2">
                      <label className="text-sm font-bold text-muted-foreground">توضیحات سایت (سئو)</label>
                      <Textarea value={settingsForm.siteDescription} onChange={e => handleSettingsChange("siteDescription", e.target.value)} placeholder="شرح مختصری درباره فروشگاه برای نمایش در موتورهای جستجو..." className="resize-none bg-muted/20" rows={3} />
                    </div>
                    <div className="space-y-2 md:col-span-2">
                      <label className="text-sm font-bold text-muted-foreground">آدرس فیزیکی فروشگاه</label>
                      <Textarea value={settingsForm.address} onChange={e => handleSettingsChange("address", e.target.value)} placeholder="تهران، خیابان..." className="resize-none bg-muted/20" rows={2} />
                    </div>
                  </div>
                </div>

                <div className="bg-card border rounded-3xl shadow-sm p-6 space-y-6">
                  <div className="border-b pb-4 flex justify-between items-center">
                    <div>
                      <h2 className="text-xl font-bold flex items-center gap-2">
                        <MessageSquare className="w-6 h-6 text-blue-500" /> شبکه‌های اجتماعی
                      </h2>
                      <p className="text-sm text-muted-foreground mt-1">لینک‌های ارتباط با مشتریان در وب‌سایت.</p>
                    </div>
                    <Button variant="outline" size="sm" onClick={() => handleSettingsChange("socialLinks", [...settingsForm.socialLinks, { id: Date.now().toString(), name: "لینک جدید", url: "", icon: "" }])}>+ افزودن شبکه</Button>
                  </div>
                  
                  <div className="grid grid-cols-1 gap-4">
                    {settingsForm.socialLinks.map((social: any, idx: number) => (
                      <div key={social.id || idx} className="flex flex-col sm:flex-row items-start sm:items-center gap-4 bg-muted/10 border p-3 rounded-xl hover:bg-muted/30 transition-colors">
                        <div className="w-12 h-12 rounded-xl shrink-0 overflow-hidden bg-background border flex items-center justify-center">
                          <MediaManager 
                            onChange={(val: any) => {
                              if (!val) return;
                              const newLinks = [...settingsForm.socialLinks];
                              newLinks[idx].icon = Array.isArray(val) ? val[0].url : val.url;
                              handleSettingsChange("socialLinks", newLinks);
                            }}
                            trigger={
                              <div className="w-full h-full cursor-pointer flex items-center justify-center relative hover:bg-muted/50 transition-colors">
                                {social.icon ? (
                                  <img src={social.icon} className="w-full h-full object-cover" alt="Icon" />
                                ) : (
                                  <div className="text-[10px] text-center text-muted-foreground font-bold p-1">آیکون</div>
                                )}
                              </div>
                            }
                          />
                        </div>
                        
                        <div className="flex-1 space-y-1 w-full">
                          <label className="text-xs font-bold text-muted-foreground">نام شبکه (نمایشی)</label>
                          <Input value={social.name} onChange={e => {
                            const newLinks = [...settingsForm.socialLinks];
                            newLinks[idx].name = e.target.value;
                            handleSettingsChange("socialLinks", newLinks);
                          }} placeholder="مثلاً اینستاگرام" className="h-8" />
                        </div>

                        <div className="flex-[2] space-y-1 w-full">
                          <label className="text-xs font-bold text-muted-foreground">لینک کامل (URL)</label>
                          <Input dir="ltr" value={social.url} onChange={e => {
                            const newLinks = [...settingsForm.socialLinks];
                            newLinks[idx].url = e.target.value;
                            handleSettingsChange("socialLinks", newLinks);
                          }} placeholder="https://..." className="h-8 text-left font-sans" />
                        </div>

                        <Button variant="ghost" size="icon" className="h-8 w-8 mt-5 text-rose-500 hover:bg-rose-100 shrink-0" onClick={() => {
                          const newLinks = [...settingsForm.socialLinks];
                          newLinks.splice(idx, 1);
                          handleSettingsChange("socialLinks", newLinks);
                        }}>
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    ))}
                    
                    {settingsForm.socialLinks.length === 0 && (
                      <div className="text-center py-6 text-muted-foreground text-sm border-2 border-dashed rounded-xl">هیچ شبکه اجتماعی تعریف نشده است.</div>
                    )}
                  </div>
                </div>
              </TabsContent>

              {/* Sales, Tax, Reviews */}
              <TabsContent value="sales" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
                {/* USD Pricing */}
                <div className="bg-card border border-violet-200 dark:border-violet-900/30 rounded-3xl shadow-sm overflow-hidden relative">
                  <div className="absolute top-0 left-0 w-40 h-40 bg-violet-500/10 rounded-br-full blur-2xl -z-0"></div>
                  <div className="bg-violet-500/10 p-5 border-b border-violet-500/20 relative z-10">
                    <h2 className="text-xl font-bold text-violet-700 dark:text-violet-400 flex gap-2 items-center">
                      <DollarSign className="w-6 h-6" /> بروزرسانی دسته‌جمعی قیمت‌ها با نرخ ارز
                    </h2>
                  </div>
                  <div className="p-6 space-y-6 relative z-10">
                    <p className="text-sm text-muted-foreground leading-relaxed">
                      با وارد کردن نرخ روز دلار (تومان)، سیستم تمامی محصولاتی که قیمت ارزی (USD) برای آن‌ها تعریف کرده‌اید را پیدا کرده و معادل ریالی آن‌ها را به صورت خودکار بروزرسانی می‌کند.
                    </p>
                    <div className="flex flex-col sm:flex-row gap-4 items-center bg-background p-4 rounded-2xl border">
                      <div className="relative flex-1 w-full">
                        <DollarSign className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-violet-500" />
                        <Input
                          type="number"
                          placeholder="مثلاً: 75000"
                          className="pr-12 h-12 text-lg font-bold font-sans text-left border-violet-200 focus-visible:ring-violet-500"
                          dir="ltr"
                          value={usdRate}
                          onChange={e => setUsdRate(e.target.value)}
                        />
                      </div>
                      <span className="text-sm font-bold text-muted-foreground shrink-0 hidden sm:block">تومان / دلار</span>
                      <Button
                        onClick={handleBulkPriceUpdate}
                        disabled={updatingPrices || !usdRate}
                        size="lg"
                        className="bg-violet-600 hover:bg-violet-700 text-white shadow-md hover:shadow-lg w-full sm:w-auto"
                      >
                        <RefreshCw className={`w-5 h-5 ml-2 ${updatingPrices ? "animate-spin" : ""}`} />
                        {updatingPrices ? "در حال بروزرسانی..." : "اعمال نرخ روز"}
                      </Button>
                    </div>
                  </div>
                </div>

                {/* Taxes */}
                <div className="bg-card border rounded-3xl shadow-sm p-6 space-y-6">
                  <div className="border-b pb-4">
                    <h2 className="text-xl font-bold flex items-center gap-2">
                      <Percent className="w-6 h-6 text-indigo-500" /> تنظیمات مالیات بر ارزش افزوده
                    </h2>
                    <p className="text-sm text-muted-foreground mt-1">مدیریت مالیات در سبد خرید و صندوق فروش.</p>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="flex items-center justify-between p-5 border rounded-2xl bg-muted/10 hover:bg-muted/30 transition-colors">
                      <div className="space-y-1">
                        <label className="text-base font-bold text-foreground cursor-pointer">محاسبه مالیات در فاکتورها</label>
                        <p className="text-xs text-muted-foreground">مالیات بر روی مجموع مبلغ اقلام اعمال می‌شود</p>
                      </div>
                      <Switch checked={settingsForm.taxEnabled} onCheckedChange={c => handleSettingsChange("taxEnabled", c)} />
                    </div>
                    <div className="space-y-3 p-5 border rounded-2xl bg-muted/10">
                      <label className="text-sm font-bold text-muted-foreground">نرخ مالیات (درصد)</label>
                      <div className="flex items-center gap-3">
                        <Input 
                          type="number" 
                          dir="ltr" 
                          disabled={!settingsForm.taxEnabled}
                          value={settingsForm.taxRate} 
                          onChange={e => handleSettingsChange("taxRate", parseFloat(e.target.value) || 0)} 
                          className="h-12 text-lg font-bold bg-background"
                        />
                        <span className="text-xl font-bold text-muted-foreground">%</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Reviews */}
                <div className="bg-card border rounded-3xl shadow-sm p-6 space-y-6">
                  <div className="border-b pb-4">
                    <h2 className="text-xl font-bold flex items-center gap-2">
                      <MessageSquare className="w-6 h-6 text-emerald-500" /> مدیریت نقد و بررسی
                    </h2>
                    <p className="text-sm text-muted-foreground mt-1">تنظیمات مربوط به نظرات کاربران درباره محصولات.</p>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="flex items-center justify-between p-5 border rounded-2xl bg-muted/10 hover:bg-muted/30 transition-colors">
                      <div className="space-y-1">
                        <label className="text-base font-bold text-foreground cursor-pointer">انتشار خودکار نظرات</label>
                        <p className="text-xs text-muted-foreground">بدون نیاز به تایید مدیریت، فوراً منتشر شوند</p>
                      </div>
                      <Switch checked={settingsForm.reviewsAutoApprove} onCheckedChange={c => handleSettingsChange("reviewsAutoApprove", c)} />
                    </div>
                    <div className="flex items-center justify-between p-5 border rounded-2xl bg-muted/10 hover:bg-muted/30 transition-colors">
                      <div className="space-y-1">
                        <label className="text-base font-bold text-foreground cursor-pointer">امکان آپلود عکس/ویدیو</label>
                        <p className="text-xs text-muted-foreground">کاربران بتوانند رسانه پیوست کنند</p>
                      </div>
                      <Switch checked={settingsForm.reviewsAllowMedia} onCheckedChange={c => handleSettingsChange("reviewsAllowMedia", c)} />
                    </div>
                  </div>
                </div>
              </TabsContent>

              {/* Hardware & Sync */}
              <TabsContent value="hardware" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
                {/* Online Server Connection */}
                <div className="bg-card border rounded-3xl shadow-sm p-6 space-y-6 relative overflow-hidden">
                  <div className="absolute top-0 right-0 w-32 h-32 bg-blue-500/10 rounded-bl-full -z-0 blur-xl"></div>
                  <div className="border-b pb-4 relative z-10">
                    <h2 className="text-xl font-bold flex items-center gap-2 text-blue-600 dark:text-blue-400">
                      <Globe className="w-6 h-6" /> اتصال به سرور آنلاین (همگام‌سازی)
                    </h2>
                    <p className="text-sm text-muted-foreground mt-1">ارتباط نرم‌افزار با فروشگاه اینترنتی (وب‌سایت) شما.</p>
                  </div>
                  <div className="space-y-3 relative z-10 p-5 bg-muted/20 border rounded-2xl">
                    <label className="text-sm font-bold text-foreground">آدرس سرور فروشگاه آنلاین</label>
                    <Input dir="ltr" value={settingsForm.onlineServerUrl} onChange={e => handleSettingsChange("onlineServerUrl", e.target.value)} placeholder="https://myshop.com" className="h-12 bg-background font-sans text-lg" />
                    <p className="text-xs text-muted-foreground leading-relaxed mt-2">با وارد کردن این آدرس، سیستم توکان ویندوز قادر خواهد بود محصولات، موجودی‌ها، قیمت‌ها و تصاویر را با دیتابیس MySQL توکان آنلاین در سرور شما همگام‌سازی (Sync) کند.</p>
                  </div>
                </div>

                {/* Hardware Printers */}
                <div className="bg-card border rounded-3xl shadow-sm p-6 space-y-6">
                  <div className="border-b pb-4">
                    <h2 className="text-xl font-bold flex items-center gap-2">
                      <Printer className="w-6 h-6 text-slate-700" /> سخت‌افزار و چاپگرها (Silent Print)
                    </h2>
                    <p className="text-sm text-muted-foreground mt-1">پیکربندی چاپگرها برای استفاده در صندوق فروش و انبار.</p>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-3 p-5 bg-muted/10 border rounded-2xl">
                      <label className="text-sm font-bold text-foreground block">نام چاپگر فیش (۸۰ میلیمتری)</label>
                      <Select value={settingsForm.receiptPrinter} onValueChange={v => handleSettingsChange("receiptPrinter", v)}>
                        <SelectTrigger dir="rtl" className="h-12 bg-background">
                          <SelectValue placeholder="انتخاب چاپگر..." />
                        </SelectTrigger>
                        <SelectContent dir="rtl">
                          <SelectItem value="none">بدون پرینتر (عدم چاپ)</SelectItem>
                          <SelectItem value="default">پرینتر پیش‌فرض سیستم</SelectItem>
                          {systemPrinters.map(p => (
                            <SelectItem key={p.name} value={p.name}>{p.name} {p.isDefault && "(پیش‌فرض)"}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">جهت چاپ خودکار فاکتورهای صندوق فروش (POS).</p>
                    </div>
                    
                    <div className="space-y-3 p-5 bg-muted/10 border rounded-2xl">
                      <label className="text-sm font-bold text-foreground block">نام چاپگر لیبل (برچسب/بارکد)</label>
                      <Select value={settingsForm.labelPrinter} onValueChange={v => handleSettingsChange("labelPrinter", v)}>
                        <SelectTrigger dir="rtl" className="h-12 bg-background">
                          <SelectValue placeholder="انتخاب چاپگر..." />
                        </SelectTrigger>
                        <SelectContent dir="rtl">
                          <SelectItem value="none">بدون پرینتر (عدم چاپ)</SelectItem>
                          <SelectItem value="default">پرینتر پیش‌فرض سیستم</SelectItem>
                          {systemPrinters.map(p => (
                            <SelectItem key={p.name} value={p.name}>{p.name} {p.isDefault && "(پیش‌فرض)"}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">جهت تولید بارکد محصول و برچسب‌های پستی.</p>
                    </div>
                  </div>
                </div>
              </TabsContent>

              {/* System, Backup, License */}
              <TabsContent value="system" className="m-0 space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
                {/* Backup & Restore */}
                <div className="bg-card border rounded-3xl shadow-sm overflow-hidden">
                  <div className="bg-amber-500/10 p-5 border-b border-amber-500/20">
                    <h2 className="text-xl font-bold text-amber-600 dark:text-amber-500 flex gap-2 items-center">
                      <DatabaseIcon className="w-6 h-6" /> پشتیبان‌گیری و بازگردانی
                    </h2>
                    <p className="text-sm text-amber-700/70 dark:text-amber-400/70 mt-1">محافظت از اطلاعات حیاتی سیستم و بازگردانی در مواقع بحرانی.</p>
                  </div>
                  <div className="p-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                      <div className="space-y-4 p-5 border rounded-2xl bg-card shadow-sm flex flex-col justify-between">
                        <div>
                          <h3 className="font-bold flex items-center gap-2 text-base"><DownloadCloudIcon className="w-5 h-5 text-emerald-500" /> تهیه پشتیبان سازمانی</h3>
                          <p className="text-xs text-muted-foreground mt-2 leading-relaxed">از کل پایگاه داده و فایل‌های نرم‌افزار یک فایل فشرده امن (ZIP) تهیه می‌شود.</p>
                        </div>
                        <Button type="button" onClick={handleBackup} className="w-full bg-emerald-600 hover:bg-emerald-700 mt-4 shadow-sm">
                          تهیه فایل پشتیبان
                        </Button>
                      </div>
                      
                      <div className="space-y-4 p-5 border border-rose-500/20 rounded-2xl bg-rose-50/50 dark:bg-rose-950/20 shadow-sm flex flex-col justify-between">
                        <div>
                          <h3 className="font-bold flex items-center gap-2 text-base text-rose-600"><UploadCloudIcon className="w-5 h-5" /> بازگردانی اطلاعات (Restore)</h3>
                          <p className="text-xs text-rose-600/70 mt-2 leading-relaxed">فایل پشتیبان را انتخاب کنید. توجه: تمام اطلاعات فعلی جایگزین خواهند شد!</p>
                        </div>
                        <input type="file" accept=".zip" className="hidden" ref={fileInputRef} onChange={handleRestore} />
                        <Button type="button" variant="destructive" onClick={() => fileInputRef.current?.click()} className="w-full mt-4 shadow-sm">
                          انتخاب فایل پشتیبان
                        </Button>
                      </div>
                      
                      <div className="space-y-4 p-5 border border-blue-500/20 rounded-2xl bg-blue-50/50 dark:bg-blue-950/20 shadow-sm md:col-span-2">
                        <div className="flex items-start gap-4">
                          <div className="w-12 h-12 bg-blue-100 dark:bg-blue-900/50 text-blue-600 rounded-2xl flex items-center justify-center shrink-0">
                            <CloudIcon className="w-6 h-6" />
                          </div>
                          <div>
                            <h3 className="font-bold text-base text-blue-700 dark:text-blue-400">ریکاوری هوشمند از سرور آنلاین</h3>
                            <p className="text-sm text-blue-600/70 dark:text-blue-400/70 mt-1">اگر سیستم لوکال خراب شد، می‌توانید با یک کلیک کل اطلاعات را از هاست/سرور آنلاین دانلود و جایگزین کنید.</p>
                          </div>
                        </div>
                        <Button type="button" disabled={recoveringServer} onClick={() => setShowRecoveryConfirm(true)} className="w-full md:w-1/3 bg-blue-600 hover:bg-blue-700 shadow-sm">
                          {recoveringServer ? "در حال دریافت..." : "شروع ریکاوری از سرور"}
                        </Button>
                      </div>
                    </div>
                    
                    {/* Backup List */}
                    <div className="border border-border/50 rounded-2xl overflow-hidden">
                      <div className="bg-muted/30 px-5 py-3 border-b border-border/50 flex items-center gap-2">
                        <DatabaseIcon className="w-4 h-4 text-muted-foreground"/> 
                        <h3 className="font-bold text-sm">آرشیو نسخه‌های پشتیبان تهیه شده</h3>
                      </div>
                      <div className="p-2 max-h-60 overflow-y-auto">
                        {backupsList.length === 0 ? (
                          <div className="text-center py-8 text-muted-foreground text-sm">هیچ فایل پشتیبانی در سیستم ثبت نشده است.</div>
                        ) : (
                          <div className="space-y-1">
                            {backupsList.map((bk, idx) => (
                              <div key={idx} className="flex justify-between items-center p-3 hover:bg-muted/30 rounded-xl transition-colors">
                                <div className="flex flex-col">
                                  <span className="font-bold text-sm" dir="ltr">{bk.filename}</span>
                                  <span className="text-xs text-muted-foreground mt-0.5">{bk.size}</span>
                                </div>
                                <a href={bk.url} download className="text-indigo-600 hover:bg-indigo-50 px-4 py-1.5 rounded-lg text-sm font-bold transition-colors">دانلود</a>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* License & Update */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  {/* License Card */}
                  <BorderGlow color={style.glow} wrapperClassName="shadow-lg h-full" className={`bg-gradient-to-br ${style.gradient} rounded-3xl border ${style.border} overflow-hidden relative h-full flex flex-col`}>
                    <div className="absolute top-0 right-0 w-64 h-64 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2 z-0 opacity-20" style={{ background: style.glow }} />
                    <div className="p-6 relative z-10 flex-1 flex flex-col">
                      <div className="flex items-center gap-4 mb-6">
                        <div className={`w-14 h-14 bg-black/40 border rounded-2xl flex items-center justify-center shrink-0 shadow-inner ${style.border}`}>
                          <ShieldAlert className={`w-7 h-7 ${style.icon}`} />
                        </div>
                        <div>
                          <h3 className="text-xl font-black text-white mb-1">اعتبار نرم‌افزار</h3>
                          {planType && (
                            <span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${style.badge}`}>
                              {style.emoji} پلن {planName || style.label}
                            </span>
                          )}
                        </div>
                      </div>
                      
                      <div className="bg-black/40 border border-white/10 rounded-2xl p-4 text-center backdrop-blur-md mt-auto">
                        <p className="text-xs text-white/60 font-bold mb-2">انقضای لایسنس فعلی</p>
                        {initialSettings?.licenseValidUntil ? (
                          <p className="text-2xl font-black text-white font-mono tracking-tight" dir="ltr">
                            {new Date(initialSettings.licenseValidUntil).getTime() === 0 ? "باطل شده" : format(new Date(initialSettings.licenseValidUntil), "yyyy/MM/dd")}
                          </p>
                        ) : (
                          <p className="text-lg font-black text-rose-400 mb-2">پیکربندی نشده</p>
                        )}
                        <a href="#" onClick={(e) => {
                          e.preventDefault();
                          const url = "https://qocteam.com/tukan";
                          if (typeof window !== 'undefined' && 'require' in window && navigator.userAgent.includes('Electron')) {
                            try { const electron = (window as any).require('electron'); electron.shell.openExternal(url); return; } catch(err) {}
                          }
                          window.open(url, "_blank");
                        }} className="mt-4 flex items-center justify-center gap-2 bg-white/10 hover:bg-white/20 border border-white/20 text-white font-bold py-2 px-4 rounded-xl transition-all text-sm">مدیریت لایسنس / تمدید</a>
                      </div>
                    </div>
                  </BorderGlow>

                  {/* Software Update Card */}
                  <div className="bg-card border rounded-3xl shadow-sm overflow-hidden h-full flex flex-col">
                    <div className="bg-muted/30 p-5 border-b flex items-center gap-3">
                      <div className="w-10 h-10 bg-indigo-100 text-indigo-600 rounded-xl flex items-center justify-center">
                        <PackageIcon className="w-5 h-5" />
                      </div>
                      <div>
                        <h2 className="font-bold text-lg">بروزرسانی توکان</h2>
                        <p className="text-xs text-muted-foreground font-mono mt-0.5" dir="ltr">Version 1.0.0</p>
                      </div>
                    </div>
                    <div className="p-6 flex-1 flex flex-col">
                      <Button
                        variant="outline"
                        disabled={updateState.checking}
                        onClick={async () => {
                          setUpdateState({ checking: true, result: null });
                          try {
                            const hubUrl = settingsForm?.onlineServerUrl ? 'https://hub.qocteam.com' : 'https://hub.qocteam.com';
                            const res = await fetch(`${hubUrl}/api/updates/check?product=TUKAN_WIN&currentVersion=1.0.0`);
                            const data = await res.json();
                            setUpdateState({ checking: false, result: data });
                          } catch (e) {
                            setUpdateState({ checking: false, result: { hasUpdate: false, error: 'خطا در ارتباط با سرور بروزرسانی' } });
                          }
                        }}
                        className="gap-2 w-full h-12 text-md shadow-sm"
                      >
                        <RefreshCwIcon className={`w-5 h-5 ${updateState.checking ? 'animate-spin' : ''}`} />
                        {updateState.checking ? 'در حال بررسی...' : 'بررسی وجود نسخه جدید'}
                      </Button>

                      {updateState.result && (
                        <div className={`mt-6 p-5 rounded-2xl border ${updateState.result.hasUpdate ? 'bg-emerald-50/50 border-emerald-200' : 'bg-muted/20'}`}>
                          {updateState.result.hasUpdate ? (
                            <div className="space-y-4">
                              <div className="flex items-center gap-2">
                                <CheckCircle2 className="w-5 h-5 text-emerald-600" />
                                <span className="font-bold text-emerald-700">نسخه جدید {updateState.result.version} موجود است!</span>
                              </div>
                              {updateState.result.changelog && (
                                <div className="text-xs text-muted-foreground whitespace-pre-line bg-background p-3 rounded-xl border leading-relaxed">
                                  {updateState.result.changelog}
                                </div>
                              )}
                              <a
                                href={updateState.result.downloadUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex justify-center items-center gap-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2.5 px-4 rounded-xl transition-colors text-sm shadow-md"
                              >
                                <DownloadIcon className="w-4 h-4" />
                                دانلود نسخه جدید سیستم
                              </a>
                            </div>
                          ) : (
                            <div className="flex items-center justify-center gap-2 text-muted-foreground p-4">
                              <CheckCircle2 className="w-5 h-5 text-emerald-500" />
                              <span className="font-bold text-sm">{updateState.result.error || updateState.result.message || 'سیستم شما کاملا بروز است.'}</span>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                
                {/* Restore Confirmation Dialog remains unchanged */}
                <AlertDialog open={showRecoveryConfirm} onOpenChange={setShowRecoveryConfirm}>
                  <AlertDialogContent dir="rtl">
                    <AlertDialogHeader>
                      <AlertDialogTitle className="flex items-center gap-2 text-blue-600">
                        <CloudIcon className="w-5 h-5" />
                        تأیید دریافت اطلاعات آنلاین
                      </AlertDialogTitle>
                      <AlertDialogDescription className="text-right space-y-2">
                        <p>این عملیات <strong>تمام اطلاعات پایگاه داده</strong> را از سرور آنلاین دریافت کرده و فایل‌های فیزیکی (عکس‌ها و آپلودها) را بازگردانی می‌کند.</p>
                        <p className="text-amber-600 font-semibold">⚠️ این عملیات ممکن است چند دقیقه طول بکشد و سیستم مجدداً راه‌اندازی خواهد شد.</p>
                        <p>آیا مطمئن هستید؟</p>
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter className="flex-row-reverse gap-2">
                      <AlertDialogCancel>انصراف</AlertDialogCancel>
                      <AlertDialogAction onClick={fullServerRecovery} className="bg-blue-600 hover:bg-blue-700">
                        بله، دریافت و بازگردانی شود
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>

              </TabsContent>

            </div>
          </Tabs>
        </div>
      </main>
    </div>
  );
}
