import { useState, useEffect, useMemo, type ReactNode } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { usePermissions } from "@/hooks/use-permissions";
import { supabase } from "@/integrations/supabase/client";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Building2,
  FileText,
  DollarSign,
  Users,
  MapPin,
  Package,
  UserCircle,
  CreditCard,
  Bell,
  Database,
  Settings as SettingsIcon,
  ShieldCheck,
  Sparkles,
  ChevronRight,
  Upload,
} from "lucide-react";

export const Route = createFileRoute("/_authenticated/settings")({
  head: () => ({
    meta: [
      { title: "Settings — Niyamah Electric & Hardware" },
      { name: "description", content: "Complete ERP settings management" },
    ],
  }),
  component: SettingsPage,
});

type SettingsMap = Record<string, string>;

const DEFAULTS: SettingsMap = {
  // Company
  company_name: "Niyamah Electric & Hardware",
  company_logo_url: "",
  invoice_banner_url: "",
  company_mobile: "",
  company_email: "",
  company_address: "",
  company_website: "",
  trade_license_no: "",
  vat_tin_no: "",
  // Invoice
  invoice_prefix: "INV-",
  invoice_auto_generate: "true",
  invoice_size: "A4",
  invoice_header_text: "",
  invoice_footer_text: "ধন্যবাদ! আবার আসবেন।",
  invoice_print_logo: "true",
  invoice_show_barcode: "true",
  invoice_terms: "",
  // Currency / Financial
  currency_symbol: "৳",
  currency_decimals: "2",
  default_vat_percent: "0",
  discount_type: "flat",
  profit_calc_method: "average",
  // User / Permission
  password_min_length: "8",
  session_timeout_min: "60",
  max_login_attempts: "5",
  // Branch / Godown
  default_branch_id: "",
  default_godown_id: "",
  transfer_approval_required: "false",
  // Product
  sku_auto_generate: "true",
  barcode_prefix: "P",
  multi_unit_enabled: "true",
  multi_price_enabled: "true",
  low_stock_threshold: "10",
  // Customer
  customer_id_auto_generate: "true",
  referral_system_enabled: "true",
  wallet_system_enabled: "true",
  default_due_limit: "0",
  // Payment
  pay_cash_enabled: "true",
  pay_bank_enabled: "true",
  pay_bkash_enabled: "true",
  pay_nagad_enabled: "true",
  pay_rocket_enabled: "true",
  pay_cheque_enabled: "true",
  pay_online_enabled: "false",
  bank_account_no: "",
  bkash_number: "",
  nagad_number: "",
  rocket_number: "",
  // Notifications
  notif_sms_enabled: "true",
  notif_whatsapp_enabled: "false",
  notif_email_enabled: "false",
  notif_low_stock_alert: "true",
  notif_due_alert: "true",
  // Backup
  auto_backup_enabled: "false",
  backup_schedule: "weekly",
  // System
  system_language: "bn",
  system_timezone: "Asia/Dhaka",
  system_date_format: "dd/MM/yyyy",
  system_theme: "light",
  // Security
  two_factor_enabled: "false",
  ip_whitelist: "",
  // Advanced
  smtp_host: "",
  smtp_port: "587",
  smtp_user: "",
  smtp_from: "",
  api_access_enabled: "false",
};

function SettingsPage() {
  const { tr, lang } = useLanguage();
  const isBn = lang === "bn";
  const { isAdmin } = usePermissions();
  const qc = useQueryClient();

  const { data: settings = {}, isLoading } = useQuery({
    queryKey: ["business-settings-all"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("business_settings")
        .select("setting_key, setting_value");
      if (error) throw error;
      const map: SettingsMap = {};
      for (const r of data ?? []) map[r.setting_key] = r.setting_value ?? "";
      return map;
    },
  });

  const merged = useMemo<SettingsMap>(() => ({ ...DEFAULTS, ...settings }), [settings]);
  const [form, setForm] = useState<SettingsMap>(merged);

  useEffect(() => {
    setForm(merged);
  }, [merged]);

  const saveMut = useMutation({
    mutationFn: async (keys: string[]) => {
      const rows = keys.map((k) => ({ setting_key: k, setting_value: form[k] ?? "" }));
      const { error } = await supabase
        .from("business_settings")
        .upsert(rows, { onConflict: "setting_key" });
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "সফলভাবে সংরক্ষিত হয়েছে" : "Settings saved");
      qc.invalidateQueries({ queryKey: ["business-settings-all"] });
      qc.invalidateQueries({ queryKey: ["company-logo"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const set = (k: string, v: string) => setForm((p) => ({ ...p, [k]: v }));
  const bool = (k: string) => form[k] === "true";
  const setBool = (k: string, v: boolean) => set(k, v ? "true" : "false");

  const handleSave = (keys: string[]) => {
    if (!isAdmin) {
      toast.error(isBn ? "শুধু অ্যাডমিন পরিবর্তন করতে পারবেন" : "Admin only");
      return;
    }
    saveMut.mutate(keys);
  };

  // Logo / banner upload
  const uploadAsset = async (file: File, key: "company_logo_url" | "invoice_banner_url") => {
    if (!isAdmin) {
      toast.error(isBn ? "শুধু অ্যাডমিন আপলোড করতে পারবেন" : "Admin only");
      return;
    }
    try {
      const ext = file.name.split(".").pop() ?? "png";
      const path = `settings/${key}-${Date.now()}.${ext}`;
      const { error: upErr } = await supabase.storage.from("brand-logos").upload(path, file, {
        upsert: true,
        cacheControl: "3600",
      });
      if (upErr) throw upErr;
      const { data } = supabase.storage.from("brand-logos").getPublicUrl(path);
      const url = data.publicUrl;
      set(key, url);
      const { error } = await supabase
        .from("business_settings")
        .upsert([{ setting_key: key, setting_value: url }], { onConflict: "setting_key" });
      if (error) throw error;
      qc.invalidateQueries({ queryKey: ["business-settings-all"] });
      qc.invalidateQueries({ queryKey: ["company-logo"] });
      toast.success(isBn ? "আপলোড সম্পন্ন" : "Uploaded");
    } catch (e) {
      toast.error((e as Error).message);
    }
  };

  if (isLoading) {
    return (
      <PageLayout>
        <p className="text-sm text-muted-foreground">{isBn ? "লোড হচ্ছে..." : "Loading..."}</p>
      </PageLayout>
    );
  }

  const disabled = !isAdmin;

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-foreground">{tr("settingsTitle") || "Settings"}</h1>
        <p className="text-sm text-muted-foreground">
          {isBn
            ? "সম্পূর্ণ ERP সিস্টেম কনফিগারেশন"
            : "Complete ERP system configuration"}
        </p>
        {!isAdmin && (
          <p className="mt-2 text-xs text-amber-600">
            {isBn ? "শুধু দেখার অনুমতি — পরিবর্তন করতে অ্যাডমিন প্রয়োজন।" : "View only — admin required to edit."}
          </p>
        )}
      </div>

      <Tabs defaultValue="company" className="w-full">
        <div className="mb-4 overflow-x-auto">
          <TabsList className="inline-flex h-auto flex-wrap gap-1 bg-muted p-1">
            <TabsTrigger value="company" className="gap-1.5"><Building2 className="h-3.5 w-3.5" />{isBn ? "কোম্পানি" : "Company"}</TabsTrigger>
            <TabsTrigger value="invoice" className="gap-1.5"><FileText className="h-3.5 w-3.5" />{isBn ? "ইনভয়েস" : "Invoice"}</TabsTrigger>
            <TabsTrigger value="financial" className="gap-1.5"><DollarSign className="h-3.5 w-3.5" />{isBn ? "ফাইন্যান্স" : "Financial"}</TabsTrigger>
            <TabsTrigger value="users" className="gap-1.5"><Users className="h-3.5 w-3.5" />{isBn ? "ইউজার" : "Users"}</TabsTrigger>
            <TabsTrigger value="branch" className="gap-1.5"><MapPin className="h-3.5 w-3.5" />{isBn ? "ব্রাঞ্চ" : "Branch"}</TabsTrigger>
            <TabsTrigger value="product" className="gap-1.5"><Package className="h-3.5 w-3.5" />{isBn ? "পণ্য" : "Product"}</TabsTrigger>
            <TabsTrigger value="customer" className="gap-1.5"><UserCircle className="h-3.5 w-3.5" />{isBn ? "কাস্টমার" : "Customer"}</TabsTrigger>
            <TabsTrigger value="payment" className="gap-1.5"><CreditCard className="h-3.5 w-3.5" />{isBn ? "পেমেন্ট" : "Payment"}</TabsTrigger>
            <TabsTrigger value="notification" className="gap-1.5"><Bell className="h-3.5 w-3.5" />{isBn ? "নোটিফিকেশন" : "Notification"}</TabsTrigger>
            <TabsTrigger value="backup" className="gap-1.5"><Database className="h-3.5 w-3.5" />{isBn ? "ব্যাকআপ" : "Backup"}</TabsTrigger>
            <TabsTrigger value="system" className="gap-1.5"><SettingsIcon className="h-3.5 w-3.5" />{isBn ? "সিস্টেম" : "System"}</TabsTrigger>
            <TabsTrigger value="security" className="gap-1.5"><ShieldCheck className="h-3.5 w-3.5" />{isBn ? "সিকিউরিটি" : "Security"}</TabsTrigger>
            <TabsTrigger value="advanced" className="gap-1.5"><Sparkles className="h-3.5 w-3.5" />{isBn ? "অ্যাডভান্সড" : "Advanced"}</TabsTrigger>
          </TabsList>
        </div>

        {/* COMPANY */}
        <TabsContent value="company">
          <Section
            title={isBn ? "কোম্পানি তথ্য" : "Company Information"}
            onSave={() =>
              handleSave([
                "company_name",
                "company_logo_url",
                "invoice_banner_url",
                "company_mobile",
                "company_email",
                "company_address",
                "company_website",
                "trade_license_no",
                "vat_tin_no",
              ])
            }
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label={isBn ? "কোম্পানির নাম" : "Company Name"}>
              <Input value={form.company_name} onChange={(e) => set("company_name", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "লোগো" : "Logo"}>
              <div className="flex items-center gap-3">
                {form.company_logo_url && (
                  <img src={form.company_logo_url} alt="logo" className="h-12 w-12 rounded object-contain border" />
                )}
                <label className="inline-flex">
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    disabled={disabled}
                    onChange={(e) => e.target.files?.[0] && uploadAsset(e.target.files[0], "company_logo_url")}
                  />
                  <Button type="button" variant="outline" size="sm" disabled={disabled} asChild>
                    <span><Upload className="h-3.5 w-3.5 mr-1" />{isBn ? "আপলোড" : "Upload"}</span>
                  </Button>
                </label>
              </div>
            </Field>
            <Field label={isBn ? "ইনভয়েস ব্যানার" : "Invoice Banner"}>
              <div className="flex items-center gap-3">
                {form.invoice_banner_url && (
                  <img src={form.invoice_banner_url} alt="banner" className="h-12 w-24 rounded object-cover border" />
                )}
                <label className="inline-flex">
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    disabled={disabled}
                    onChange={(e) => e.target.files?.[0] && uploadAsset(e.target.files[0], "invoice_banner_url")}
                  />
                  <Button type="button" variant="outline" size="sm" disabled={disabled} asChild>
                    <span><Upload className="h-3.5 w-3.5 mr-1" />{isBn ? "আপলোড" : "Upload"}</span>
                  </Button>
                </label>
              </div>
            </Field>
            <Field label={isBn ? "মোবাইল" : "Mobile"}>
              <Input value={form.company_mobile} onChange={(e) => set("company_mobile", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ইমেইল" : "Email"}>
              <Input type="email" value={form.company_email} onChange={(e) => set("company_email", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ঠিকানা" : "Address"}>
              <Textarea value={form.company_address} onChange={(e) => set("company_address", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ওয়েবসাইট" : "Website"}>
              <Input value={form.company_website} onChange={(e) => set("company_website", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ট্রেড লাইসেন্স নং" : "Trade License No"}>
              <Input value={form.trade_license_no} onChange={(e) => set("trade_license_no", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "VAT / TIN নং" : "VAT / TIN No"}>
              <Input value={form.vat_tin_no} onChange={(e) => set("vat_tin_no", e.target.value)} disabled={disabled} />
            </Field>
          </Section>
        </TabsContent>

        {/* INVOICE */}
        <TabsContent value="invoice">
          <Section
            title={isBn ? "ইনভয়েস সেটিংস" : "Invoice Settings"}
            onSave={() =>
              handleSave([
                "invoice_prefix",
                "invoice_auto_generate",
                "invoice_size",
                "invoice_header_text",
                "invoice_footer_text",
                "invoice_print_logo",
                "invoice_show_barcode",
                "invoice_terms",
              ])
            }
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label={isBn ? "ইনভয়েস প্রিফিক্স" : "Invoice Prefix"}>
              <Input value={form.invoice_prefix} onChange={(e) => set("invoice_prefix", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "অটো নাম্বার জেনারেট" : "Auto Number Generate"}>
              <Switch checked={bool("invoice_auto_generate")} onCheckedChange={(v) => setBool("invoice_auto_generate", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ইনভয়েস সাইজ" : "Invoice Size"}>
              <Select value={form.invoice_size} onValueChange={(v) => set("invoice_size", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="A4">A4</SelectItem>
                  <SelectItem value="POS">POS (80mm)</SelectItem>
                </SelectContent>
              </Select>
            </Field>
            <Field label={isBn ? "হেডার টেক্সট" : "Header Text"}>
              <Input value={form.invoice_header_text} onChange={(e) => set("invoice_header_text", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ফুটার টেক্সট" : "Footer Text"}>
              <Input value={form.invoice_footer_text} onChange={(e) => set("invoice_footer_text", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "লোগো প্রিন্ট" : "Print Logo"}>
              <Switch checked={bool("invoice_print_logo")} onCheckedChange={(v) => setBool("invoice_print_logo", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "বারকোড দেখাও" : "Show Barcode/QR"}>
              <Switch checked={bool("invoice_show_barcode")} onCheckedChange={(v) => setBool("invoice_show_barcode", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "শর্তাবলী" : "Terms & Conditions"}>
              <Textarea value={form.invoice_terms} onChange={(e) => set("invoice_terms", e.target.value)} disabled={disabled} rows={3} />
            </Field>
          </Section>
        </TabsContent>

        {/* FINANCIAL */}
        <TabsContent value="financial">
          <Section
            title={isBn ? "মুদ্রা ও ফাইন্যান্স" : "Currency & Financial"}
            onSave={() => handleSave(["currency_symbol", "currency_decimals", "default_vat_percent", "discount_type", "profit_calc_method"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label={isBn ? "মুদ্রা প্রতীক" : "Currency Symbol"}>
              <Input value={form.currency_symbol} onChange={(e) => set("currency_symbol", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ডেসিম্যাল স্থান" : "Decimal Places"}>
              <Input type="number" min="0" max="4" value={form.currency_decimals} onChange={(e) => set("currency_decimals", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ডিফল্ট VAT %" : "Default VAT %"}>
              <Input type="number" min="0" step="0.01" value={form.default_vat_percent} onChange={(e) => set("default_vat_percent", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ডিসকাউন্ট টাইপ" : "Discount Type"}>
              <Select value={form.discount_type} onValueChange={(v) => set("discount_type", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="flat">{isBn ? "ফ্ল্যাট" : "Flat"}</SelectItem>
                  <SelectItem value="percent">{isBn ? "শতাংশ" : "Percent"}</SelectItem>
                </SelectContent>
              </Select>
            </Field>
            <Field label={isBn ? "প্রফিট হিসাব পদ্ধতি" : "Profit Calc Method"}>
              <Select value={form.profit_calc_method} onValueChange={(v) => set("profit_calc_method", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="average">{isBn ? "এভারেজ" : "Average"}</SelectItem>
                  <SelectItem value="fifo">FIFO</SelectItem>
                  <SelectItem value="last_purchase">{isBn ? "শেষ ক্রয়মূল্য" : "Last Purchase"}</SelectItem>
                </SelectContent>
              </Select>
            </Field>
          </Section>
        </TabsContent>

        {/* USERS */}
        <TabsContent value="users">
          <Section
            title={isBn ? "ইউজার ও পারমিশন" : "User & Permission"}
            onSave={() => handleSave(["password_min_length", "session_timeout_min", "max_login_attempts"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <NavLinkRow to="/admin" label={isBn ? "অ্যাডমিন প্যানেল (ইউজার ও রোল)" : "Admin Panel (Users & Roles)"} />
            <NavLinkRow to="/staff" label={isBn ? "স্টাফ ম্যানেজমেন্ট" : "Staff Management"} />
            <Field label={isBn ? "পাসওয়ার্ড মিনিমাম দৈর্ঘ্য" : "Password Min Length"}>
              <Input type="number" min="6" value={form.password_min_length} onChange={(e) => set("password_min_length", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "সেশন টাইমআউট (মিনিট)" : "Session Timeout (min)"}>
              <Input type="number" min="5" value={form.session_timeout_min} onChange={(e) => set("session_timeout_min", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "সর্বাধিক লগইন প্রচেষ্টা" : "Max Login Attempts"}>
              <Input type="number" min="1" value={form.max_login_attempts} onChange={(e) => set("max_login_attempts", e.target.value)} disabled={disabled} />
            </Field>
          </Section>
        </TabsContent>

        {/* BRANCH */}
        <TabsContent value="branch">
          <Section
            title={isBn ? "ব্রাঞ্চ ও গোডাউন" : "Branch & Godown"}
            onSave={() => handleSave(["default_branch_id", "default_godown_id", "transfer_approval_required"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <NavLinkRow to="/branches" label={isBn ? "ব্রাঞ্চ ম্যানেজমেন্ট" : "Branch Management"} />
            <NavLinkRow to="/godowns" label={isBn ? "গোডাউন ম্যানেজমেন্ট" : "Godown Management"} />
            <Field label={isBn ? "ডিফল্ট ব্রাঞ্চ ID" : "Default Branch ID"}>
              <Input value={form.default_branch_id} onChange={(e) => set("default_branch_id", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ডিফল্ট গোডাউন ID" : "Default Godown ID"}>
              <Input value={form.default_godown_id} onChange={(e) => set("default_godown_id", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ট্রান্সফার অনুমোদন প্রয়োজন" : "Transfer Approval Required"}>
              <Switch checked={bool("transfer_approval_required")} onCheckedChange={(v) => setBool("transfer_approval_required", v)} disabled={disabled} />
            </Field>
          </Section>
        </TabsContent>

        {/* PRODUCT */}
        <TabsContent value="product">
          <Section
            title={isBn ? "প্রোডাক্ট সেটিংস" : "Product Settings"}
            onSave={() => handleSave(["sku_auto_generate", "barcode_prefix", "multi_unit_enabled", "multi_price_enabled", "low_stock_threshold"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label={isBn ? "SKU অটো জেনারেট" : "SKU Auto Generate"}>
              <Switch checked={bool("sku_auto_generate")} onCheckedChange={(v) => setBool("sku_auto_generate", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "বারকোড প্রিফিক্স" : "Barcode Prefix"}>
              <Input value={form.barcode_prefix} onChange={(e) => set("barcode_prefix", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "মাল্টি ইউনিট" : "Multi Unit"}>
              <Switch checked={bool("multi_unit_enabled")} onCheckedChange={(v) => setBool("multi_unit_enabled", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "মাল্টি প্রাইস" : "Multi Price"}>
              <Switch checked={bool("multi_price_enabled")} onCheckedChange={(v) => setBool("multi_price_enabled", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "লো স্টক অ্যালার্ট লিমিট" : "Low Stock Alert Limit"}>
              <Input type="number" min="0" value={form.low_stock_threshold} onChange={(e) => set("low_stock_threshold", e.target.value)} disabled={disabled} />
            </Field>
          </Section>
        </TabsContent>

        {/* CUSTOMER */}
        <TabsContent value="customer">
          <Section
            title={isBn ? "কাস্টমার সেটিংস" : "Customer Settings"}
            onSave={() => handleSave(["customer_id_auto_generate", "referral_system_enabled", "wallet_system_enabled", "default_due_limit"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <NavLinkRow to="/customer-segments" label={isBn ? "কাস্টমার সেগমেন্ট" : "Customer Segments"} />
            <Field label={isBn ? "কাস্টমার ID অটো জেনারেট" : "Customer ID Auto Generate"}>
              <Switch checked={bool("customer_id_auto_generate")} onCheckedChange={(v) => setBool("customer_id_auto_generate", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "রেফারেল সিস্টেম" : "Referral System"}>
              <Switch checked={bool("referral_system_enabled")} onCheckedChange={(v) => setBool("referral_system_enabled", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ওয়ালেট সিস্টেম" : "Wallet System"}>
              <Switch checked={bool("wallet_system_enabled")} onCheckedChange={(v) => setBool("wallet_system_enabled", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "ডিফল্ট বাকির সীমা (৳)" : "Default Due Limit (৳)"}>
              <Input type="number" min="0" value={form.default_due_limit} onChange={(e) => set("default_due_limit", e.target.value)} disabled={disabled} />
            </Field>
          </Section>
        </TabsContent>

        {/* PAYMENT */}
        <TabsContent value="payment">
          <Section
            title={isBn ? "পেমেন্ট পদ্ধতি" : "Payment Methods"}
            onSave={() =>
              handleSave([
                "pay_cash_enabled","pay_bank_enabled","pay_bkash_enabled","pay_nagad_enabled",
                "pay_rocket_enabled","pay_cheque_enabled","pay_online_enabled",
                "bank_account_no","bkash_number","nagad_number","rocket_number",
              ])
            }
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label={isBn ? "ক্যাশ" : "Cash"}><Switch checked={bool("pay_cash_enabled")} onCheckedChange={(v) => setBool("pay_cash_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "ব্যাংক" : "Bank"}><Switch checked={bool("pay_bank_enabled")} onCheckedChange={(v) => setBool("pay_bank_enabled", v)} disabled={disabled} /></Field>
            <Field label="bKash"><Switch checked={bool("pay_bkash_enabled")} onCheckedChange={(v) => setBool("pay_bkash_enabled", v)} disabled={disabled} /></Field>
            <Field label="Nagad"><Switch checked={bool("pay_nagad_enabled")} onCheckedChange={(v) => setBool("pay_nagad_enabled", v)} disabled={disabled} /></Field>
            <Field label="Rocket"><Switch checked={bool("pay_rocket_enabled")} onCheckedChange={(v) => setBool("pay_rocket_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "চেক" : "Cheque"}><Switch checked={bool("pay_cheque_enabled")} onCheckedChange={(v) => setBool("pay_cheque_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "অনলাইন পেমেন্ট" : "Online Payment"}><Switch checked={bool("pay_online_enabled")} onCheckedChange={(v) => setBool("pay_online_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "ব্যাংক অ্যাকাউন্ট নং" : "Bank Account No"}><Input value={form.bank_account_no} onChange={(e) => set("bank_account_no", e.target.value)} disabled={disabled} /></Field>
            <Field label="bKash Number"><Input value={form.bkash_number} onChange={(e) => set("bkash_number", e.target.value)} disabled={disabled} /></Field>
            <Field label="Nagad Number"><Input value={form.nagad_number} onChange={(e) => set("nagad_number", e.target.value)} disabled={disabled} /></Field>
            <Field label="Rocket Number"><Input value={form.rocket_number} onChange={(e) => set("rocket_number", e.target.value)} disabled={disabled} /></Field>
          </Section>
        </TabsContent>

        {/* NOTIFICATION */}
        <TabsContent value="notification">
          <Section
            title={isBn ? "নোটিফিকেশন সেটিংস" : "Notification Settings"}
            onSave={() => handleSave(["notif_sms_enabled","notif_whatsapp_enabled","notif_email_enabled","notif_low_stock_alert","notif_due_alert"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <NavLinkRow to="/sms" label={isBn ? "SMS টেমপ্লেট ও সেটিংস" : "SMS Templates & Settings"} />
            <Field label={isBn ? "SMS নোটিফিকেশন" : "SMS Notification"}><Switch checked={bool("notif_sms_enabled")} onCheckedChange={(v) => setBool("notif_sms_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "WhatsApp নোটিফিকেশন" : "WhatsApp Notification"}><Switch checked={bool("notif_whatsapp_enabled")} onCheckedChange={(v) => setBool("notif_whatsapp_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "Email নোটিফিকেশন" : "Email Notification"}><Switch checked={bool("notif_email_enabled")} onCheckedChange={(v) => setBool("notif_email_enabled", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "লো স্টক অ্যালার্ট" : "Low Stock Alert"}><Switch checked={bool("notif_low_stock_alert")} onCheckedChange={(v) => setBool("notif_low_stock_alert", v)} disabled={disabled} /></Field>
            <Field label={isBn ? "বাকি অ্যালার্ট" : "Due Alert"}><Switch checked={bool("notif_due_alert")} onCheckedChange={(v) => setBool("notif_due_alert", v)} disabled={disabled} /></Field>
          </Section>
        </TabsContent>

        {/* BACKUP */}
        <TabsContent value="backup">
          <Section
            title={isBn ? "ব্যাকআপ সেটিংস" : "Backup Settings"}
            onSave={() => handleSave(["auto_backup_enabled", "backup_schedule"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <NavLinkRow to="/backups" label={isBn ? "ব্যাকআপ ম্যানেজার" : "Backup Manager"} />
            <Field label={isBn ? "অটো ব্যাকআপ" : "Auto Backup"}>
              <Switch checked={bool("auto_backup_enabled")} onCheckedChange={(v) => setBool("auto_backup_enabled", v)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "শিডিউল" : "Schedule"}>
              <Select value={form.backup_schedule} onValueChange={(v) => set("backup_schedule", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="daily">{isBn ? "প্রতিদিন" : "Daily"}</SelectItem>
                  <SelectItem value="weekly">{isBn ? "সাপ্তাহিক" : "Weekly"}</SelectItem>
                  <SelectItem value="monthly">{isBn ? "মাসিক" : "Monthly"}</SelectItem>
                </SelectContent>
              </Select>
            </Field>
          </Section>
        </TabsContent>

        {/* SYSTEM */}
        <TabsContent value="system">
          <Section
            title={isBn ? "সিস্টেম সেটিংস" : "System Settings"}
            onSave={() => handleSave(["system_language", "system_timezone", "system_date_format", "system_theme"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label={isBn ? "ভাষা" : "Language"}>
              <Select value={form.system_language} onValueChange={(v) => set("system_language", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="bn">বাংলা</SelectItem>
                  <SelectItem value="en">English</SelectItem>
                </SelectContent>
              </Select>
            </Field>
            <Field label={isBn ? "টাইমজোন" : "Timezone"}>
              <Input value={form.system_timezone} onChange={(e) => set("system_timezone", e.target.value)} disabled={disabled} />
            </Field>
            <Field label={isBn ? "তারিখ ফরম্যাট" : "Date Format"}>
              <Select value={form.system_date_format} onValueChange={(v) => set("system_date_format", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="dd/MM/yyyy">DD/MM/YYYY</SelectItem>
                  <SelectItem value="MM/dd/yyyy">MM/DD/YYYY</SelectItem>
                  <SelectItem value="yyyy-MM-dd">YYYY-MM-DD</SelectItem>
                </SelectContent>
              </Select>
            </Field>
            <Field label={isBn ? "থিম" : "Theme"}>
              <Select value={form.system_theme} onValueChange={(v) => set("system_theme", v)} disabled={disabled}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="light">{isBn ? "লাইট" : "Light"}</SelectItem>
                  <SelectItem value="dark">{isBn ? "ডার্ক" : "Dark"}</SelectItem>
                </SelectContent>
              </Select>
            </Field>
          </Section>
        </TabsContent>

        {/* SECURITY */}
        <TabsContent value="security">
          <Section
            title={isBn ? "সিকিউরিটি সেটিংস" : "Security Settings"}
            onSave={() => handleSave(["two_factor_enabled", "ip_whitelist"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            {isAdmin && (
              <NavLinkRow
                to="/sale-status-rules"
                label={isBn ? "সেল স্ট্যাটাস ট্রানজিশন নিয়মাবলী" : "Sale Status Transition Rules"}
              />
            )}
            <Field label={isBn ? "টু-ফ্যাক্টর লগইন (ভবিষ্যৎ)" : "Two-Factor Login (Future)"}>
              <Switch checked={bool("two_factor_enabled")} onCheckedChange={(v) => setBool("two_factor_enabled", v)} disabled />
            </Field>
            <Field label={isBn ? "IP হোয়াইটলিস্ট (কমা-আলাদা)" : "IP Whitelist (comma-separated)"}>
              <Textarea value={form.ip_whitelist} onChange={(e) => set("ip_whitelist", e.target.value)} disabled={disabled} rows={3} placeholder="192.168.1.1, 10.0.0.5" />
            </Field>
          </Section>
        </TabsContent>

        {/* ADVANCED */}
        <TabsContent value="advanced">
          <Section
            title={isBn ? "অ্যাডভান্সড সেটিংস" : "Advanced Settings"}
            onSave={() => handleSave(["smtp_host", "smtp_port", "smtp_user", "smtp_from", "api_access_enabled"])}
            saving={saveMut.isPending}
            disabled={disabled}
          >
            <Field label="SMTP Host"><Input value={form.smtp_host} onChange={(e) => set("smtp_host", e.target.value)} disabled={disabled} /></Field>
            <Field label="SMTP Port"><Input type="number" value={form.smtp_port} onChange={(e) => set("smtp_port", e.target.value)} disabled={disabled} /></Field>
            <Field label="SMTP User"><Input value={form.smtp_user} onChange={(e) => set("smtp_user", e.target.value)} disabled={disabled} /></Field>
            <Field label="SMTP From Email"><Input type="email" value={form.smtp_from} onChange={(e) => set("smtp_from", e.target.value)} disabled={disabled} /></Field>
            <Field label={isBn ? "API অ্যাক্সেস" : "API Access"}><Switch checked={bool("api_access_enabled")} onCheckedChange={(v) => setBool("api_access_enabled", v)} disabled={disabled} /></Field>
          </Section>
        </TabsContent>
      </Tabs>
    </PageLayout>
  );
}

function Section({
  title,
  children,
  onSave,
  saving,
  disabled,
}: {
  title: string;
  children: ReactNode;
  onSave: () => void;
  saving: boolean;
  disabled: boolean;
}) {
  return (
    <div className="rounded-xl border border-border bg-card p-6">
      <h2 className="mb-4 text-sm font-bold text-foreground">{title}</h2>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">{children}</div>
      <div className="mt-6 flex justify-end">
        <Button onClick={onSave} disabled={saving || disabled}>
          {saving ? "Saving..." : "Save"}
        </Button>
      </div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs text-muted-foreground">{label}</Label>
      <div>{children}</div>
    </div>
  );
}

function NavLinkRow({ to, label }: { to: string; label: string }) {
  return (
    <Link
      to={to}
      className="md:col-span-2 flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2 hover:bg-muted/40 transition"
    >
      <span className="text-sm font-medium text-foreground">{label}</span>
      <ChevronRight className="h-4 w-4 text-muted-foreground" />
    </Link>
  );
}
