import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  Plus, Pencil, Trash2, Save, ShieldAlert, Settings as SettingsIcon, Power,
  CalendarClock, Layers, Tag, Package,
} from "lucide-react";

export const Route = createFileRoute("/_authenticated/commission-settings")({
  head: () => ({ meta: [{ title: "Commission Settings — Niyamah ERP" }] }),
  component: CommissionSettingsPage,
});

type Rule = {
  id: string;
  name: string;
  commission_type: string;
  commission_value: number;
  min_sale_amount: number;
  max_sale_amount: number | null;
  priority: number;
  is_active: boolean;
  note: string | null;
  level: number;
  category_id: string | null;
  product_id: string | null;
  starts_at: string | null;
  ends_at: string | null;
};

type PayoutSchedule = {
  id: string;
  auto_enabled: boolean;
  frequency: string;
  day_of_week: number;
  day_of_month: number;
  min_payout_amount: number;
  last_run_at: string | null;
  next_run_at: string | null;
};

function CommissionSettingsPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const qc = useQueryClient();
  const { user } = useAuth();

  const { data: isAdmin = false } = useQuery({
    queryKey: ["is-admin", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", user!.id).eq("role", "admin").maybeSingle();
      return !!data;
    },
  });

  const { data: settings = [] } = useQuery({
    queryKey: ["commission-global"],
    queryFn: async () => {
      const { data } = await supabase.from("business_settings").select("*").in("setting_key", [
        "referral_enabled", "referral_default_type", "referral_default_value", "withdrawal_minimum",
      ]);
      return data || [];
    },
  });

  const getSetting = (k: string) => settings.find((s: any) => s.setting_key === k)?.setting_value || "";
  const [edits, setEdits] = useState<Record<string, string>>({});
  const val = (k: string) => edits[k] ?? getSetting(k);

  const saveSettings = useMutation({
    mutationFn: async () => {
      for (const [k, v] of Object.entries(edits)) {
        await supabase.from("business_settings").upsert({ setting_key: k, setting_value: v, updated_by: user?.id }, { onConflict: "setting_key" });
      }
    },
    onSuccess: () => { toast.success(isBn ? "সেটিংস সংরক্ষিত" : "Settings saved"); setEdits({}); qc.invalidateQueries({ queryKey: ["commission-global"] }); },
    onError: (e: any) => toast.error(e.message),
  });

  const { data: rules = [] } = useQuery({
    queryKey: ["commission-rules"],
    queryFn: async () => {
      const { data } = await supabase.from("commission_rules").select("*").order("priority", { ascending: false }).order("level", { ascending: true }).order("created_at", { ascending: false });
      return (data || []) as Rule[];
    },
  });

  const { data: categories = [] } = useQuery({
    queryKey: ["cat-list-min"],
    queryFn: async () => {
      const { data } = await supabase.from("categories").select("id,name,name_bn").eq("status", "active").order("name");
      return data || [];
    },
  });

  const { data: products = [] } = useQuery({
    queryKey: ["prod-list-min"],
    queryFn: async () => {
      const { data } = await supabase.from("products").select("id,name,name_bn").eq("is_deleted", false).order("name").limit(500);
      return data || [];
    },
  });

  const { data: payout } = useQuery({
    queryKey: ["commission-payout-schedule"],
    queryFn: async () => {
      const { data } = await supabase.from("commission_payout_schedule").select("*").limit(1).maybeSingle();
      return data as PayoutSchedule | null;
    },
  });

  const [showForm, setShowForm] = useState(false);
  const [editRule, setEditRule] = useState<Rule | null>(null);
  const [deleteRule, setDeleteRule] = useState<Rule | null>(null);

  const upsertRule = useMutation({
    mutationFn: async (r: Partial<Rule>) => {
      if (!r.name?.trim()) throw new Error(isBn ? "নাম দরকার" : "Name required");
      if (editRule) {
        const { error } = await supabase.from("commission_rules").update(r).eq("id", editRule.id);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("commission_rules").insert({ ...(r as any), created_by: user?.id });
        if (error) throw error;
      }
    },
    onSuccess: () => { toast.success(isBn ? "সংরক্ষিত" : "Saved"); setShowForm(false); setEditRule(null); qc.invalidateQueries({ queryKey: ["commission-rules"] }); },
    onError: (e: any) => toast.error(e.message),
  });

  const toggleRule = useMutation({
    mutationFn: async (r: Rule) => {
      const { error } = await supabase.from("commission_rules").update({ is_active: !r.is_active }).eq("id", r.id);
      if (error) throw error;
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["commission-rules"] }),
  });

  const delRule = useMutation({
    mutationFn: async () => {
      if (!deleteRule) return;
      const { error } = await supabase.from("commission_rules").delete().eq("id", deleteRule.id);
      if (error) throw error;
    },
    onSuccess: () => { toast.success(isBn ? "মুছে ফেলা হয়েছে" : "Deleted"); setDeleteRule(null); qc.invalidateQueries({ queryKey: ["commission-rules"] }); },
    onError: (e: any) => toast.error(e.message),
  });

  const [payoutEdits, setPayoutEdits] = useState<Partial<PayoutSchedule>>({});
  const pv = <K extends keyof PayoutSchedule>(k: K): any => (payoutEdits as any)[k] ?? (payout?.[k] as any);
  const savePayout = useMutation({
    mutationFn: async () => {
      if (!payout?.id) {
        const { error } = await supabase.from("commission_payout_schedule").insert({
          ...(payoutEdits as any), updated_by: user?.id,
        });
        if (error) throw error;
      } else {
        const { error } = await supabase.from("commission_payout_schedule")
          .update({ ...payoutEdits, updated_by: user?.id })
          .eq("id", payout.id);
        if (error) throw error;
      }
    },
    onSuccess: () => { toast.success(isBn ? "পেআউট শিডিউল সংরক্ষিত" : "Payout schedule saved"); setPayoutEdits({}); qc.invalidateQueries({ queryKey: ["commission-payout-schedule"] }); },
    onError: (e: any) => toast.error(e.message),
  });

  if (!isAdmin) {
    return (
      <PageLayout>
        <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-8 text-center">
          <ShieldAlert className="h-10 w-10 mx-auto text-destructive mb-2" />
          <h1 className="text-xl font-bold">{isBn ? "অনুমতি নেই" : "Permission denied"}</h1>
        </div>
      </PageLayout>
    );
  }

  const catName = (id?: string | null) => {
    if (!id) return null;
    const c: any = categories.find((x: any) => x.id === id);
    return c ? (isBn ? (c.name_bn || c.name) : c.name) : null;
  };
  const prodName = (id?: string | null) => {
    if (!id) return null;
    const p: any = products.find((x: any) => x.id === id);
    return p ? (isBn ? (p.name_bn || p.name) : p.name) : null;
  };
  const fmtDate = (d?: string | null) => d ? new Date(d).toLocaleDateString() : null;

  const dayNames = isBn
    ? ["সোম", "মঙ্গল", "বুধ", "বৃহ", "শুক্র", "শনি", "রবি"]
    : ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-2xl font-bold flex items-center gap-2"><SettingsIcon className="h-6 w-6 text-primary" />{isBn ? "রেফারেল কমিশন সেটিংস" : "Referral Commission Settings"}</h1>
        <p className="text-sm text-muted-foreground">{isBn ? "গ্লোবাল সেটিংস, কমিশন রুল ও অটো-পেআউট ম্যানেজ করুন" : "Manage global settings, commission rules and auto-payout"}</p>
      </div>

      {/* Global settings */}
      <div className="rounded-2xl border border-border bg-card p-5 mb-6">
        <h2 className="font-semibold mb-4">{isBn ? "গ্লোবাল সেটিংস" : "Global Settings"}</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "রেফারেল চালু" : "Referral Enabled"}</label>
            <select value={val("referral_enabled")} onChange={(e) => setEdits((p) => ({ ...p, referral_enabled: e.target.value }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value="true">{isBn ? "হ্যাঁ" : "Yes"}</option>
              <option value="false">{isBn ? "না" : "No"}</option>
            </select>
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "ডিফল্ট ধরন" : "Default Type"}</label>
            <select value={val("referral_default_type")} onChange={(e) => setEdits((p) => ({ ...p, referral_default_type: e.target.value }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value="percentage">{isBn ? "শতাংশ (%)" : "Percentage (%)"}</option>
              <option value="fixed">{isBn ? "নির্দিষ্ট পরিমাণ" : "Fixed Amount"}</option>
            </select>
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "ডিফল্ট মান" : "Default Value"}</label>
            <input type="number" step="0.01" value={val("referral_default_value")} onChange={(e) => setEdits((p) => ({ ...p, referral_default_value: e.target.value }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "সর্বনিম্ন ক্যাশ আউট (৳)" : "Min Cash Out (৳)"}</label>
            <input type="number" step="1" value={val("withdrawal_minimum")} onChange={(e) => setEdits((p) => ({ ...p, withdrawal_minimum: e.target.value }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
        </div>
        <div className="mt-4 flex justify-end">
          <button onClick={() => saveSettings.mutate()} disabled={Object.keys(edits).length === 0 || saveSettings.isPending} className="flex items-center gap-2 rounded-lg bg-primary text-primary-foreground px-4 py-2 text-sm disabled:opacity-50">
            <Save className="h-4 w-4" />{isBn ? "সংরক্ষণ" : "Save"}
          </button>
        </div>
      </div>

      {/* Auto Payout Schedule */}
      <div className="rounded-2xl border border-border bg-card p-5 mb-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-semibold flex items-center gap-2"><CalendarClock className="h-5 w-5 text-primary" />{isBn ? "অটো-পেআউট শিডিউল" : "Auto-Payout Schedule"}</h2>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={!!pv("auto_enabled")} onChange={(e) => setPayoutEdits((p) => ({ ...p, auto_enabled: e.target.checked }))} />
            {isBn ? "চালু" : "Enabled"}
          </label>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "ফ্রিকোয়েন্সি" : "Frequency"}</label>
            <select value={pv("frequency") || "monthly"} onChange={(e) => setPayoutEdits((p) => ({ ...p, frequency: e.target.value }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value="weekly">{isBn ? "সাপ্তাহিক" : "Weekly"}</option>
              <option value="monthly">{isBn ? "মাসিক" : "Monthly"}</option>
            </select>
          </div>
          {pv("frequency") === "weekly" ? (
            <div>
              <label className="text-xs text-muted-foreground">{isBn ? "সপ্তাহের দিন" : "Day of Week"}</label>
              <select value={pv("day_of_week") || 1} onChange={(e) => setPayoutEdits((p) => ({ ...p, day_of_week: parseInt(e.target.value) }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
                {dayNames.map((d, i) => <option key={i} value={i + 1}>{d}</option>)}
              </select>
            </div>
          ) : (
            <div>
              <label className="text-xs text-muted-foreground">{isBn ? "মাসের তারিখ (1-28)" : "Day of Month (1-28)"}</label>
              <input type="number" min={1} max={28} value={pv("day_of_month") || 1} onChange={(e) => setPayoutEdits((p) => ({ ...p, day_of_month: Math.min(28, Math.max(1, parseInt(e.target.value) || 1)) }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
            </div>
          )}
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "মিনিমাম পেআউট (৳)" : "Min Payout (৳)"}</label>
            <input type="number" step="1" value={pv("min_payout_amount") ?? 0} onChange={(e) => setPayoutEdits((p) => ({ ...p, min_payout_amount: parseFloat(e.target.value) || 0 }))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div className="text-xs text-muted-foreground self-end">
            {payout?.last_run_at && <div>{isBn ? "শেষ রান:" : "Last run:"} {new Date(payout.last_run_at).toLocaleString()}</div>}
            {payout?.next_run_at && <div>{isBn ? "পরবর্তী:" : "Next:"} {new Date(payout.next_run_at).toLocaleString()}</div>}
          </div>
        </div>
        <div className="mt-4 flex justify-end">
          <button onClick={() => savePayout.mutate()} disabled={Object.keys(payoutEdits).length === 0 || savePayout.isPending} className="flex items-center gap-2 rounded-lg bg-primary text-primary-foreground px-4 py-2 text-sm disabled:opacity-50">
            <Save className="h-4 w-4" />{isBn ? "সংরক্ষণ" : "Save"}
          </button>
        </div>
      </div>

      {/* Rules list */}
      <div className="rounded-2xl border border-border bg-card overflow-hidden">
        <div className="flex items-center justify-between p-5 border-b border-border">
          <h2 className="font-semibold">{isBn ? "কমিশন রুলস" : "Commission Rules"}</h2>
          <button onClick={() => { setEditRule(null); setShowForm(true); }} className="rounded-lg bg-primary text-primary-foreground px-3 py-2 text-sm flex items-center gap-1">
            <Plus className="h-4 w-4" />{isBn ? "নতুন রুল" : "Add Rule"}
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-xs">
              <tr className="text-left">
                <th className="px-3 py-2">{isBn ? "নাম / স্কোপ" : "Name / Scope"}</th>
                <th className="px-3 py-2 text-center">{isBn ? "লেভেল" : "Level"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "মান" : "Value"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "সেল রেঞ্জ" : "Sale Range"}</th>
                <th className="px-3 py-2 text-center">{isBn ? "তারিখ" : "Dates"}</th>
                <th className="px-3 py-2 text-center">{isBn ? "প্রায়োরিটি" : "Priority"}</th>
                <th className="px-3 py-2 text-center">{isBn ? "স্ট্যাটাস" : "Status"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "অ্যাকশন" : "Action"}</th>
              </tr>
            </thead>
            <tbody>
              {rules.length === 0 && (
                <tr><td colSpan={8} className="px-3 py-8 text-center text-xs text-muted-foreground">{isBn ? "কোনো রুল নেই" : "No rules yet"}</td></tr>
              )}
              {rules.map((r) => (
                <tr key={r.id} className="border-t border-border">
                  <td className="px-3 py-2">
                    <p className="font-medium">{r.name}</p>
                    <div className="flex flex-wrap gap-1 mt-0.5">
                      {catName(r.category_id) && <span className="inline-flex items-center gap-0.5 text-[10px] bg-blue-500/10 text-blue-700 px-1.5 py-0.5 rounded"><Tag className="h-2.5 w-2.5" />{catName(r.category_id)}</span>}
                      {prodName(r.product_id) && <span className="inline-flex items-center gap-0.5 text-[10px] bg-purple-500/10 text-purple-700 px-1.5 py-0.5 rounded"><Package className="h-2.5 w-2.5" />{prodName(r.product_id)}</span>}
                    </div>
                    {r.note && <p className="text-xs text-muted-foreground mt-0.5">{r.note}</p>}
                  </td>
                  <td className="px-3 py-2 text-center"><span className="inline-flex items-center gap-0.5 text-[10px] bg-primary/10 text-primary px-1.5 py-0.5 rounded font-semibold"><Layers className="h-2.5 w-2.5" />L{r.level || 1}</span></td>
                  <td className="px-3 py-2 text-right font-semibold">{r.commission_type === "percentage" ? `${Number(r.commission_value)}%` : `৳${Number(r.commission_value).toFixed(2)}`}</td>
                  <td className="px-3 py-2 text-right text-xs">৳{Number(r.min_sale_amount).toFixed(0)}{r.max_sale_amount ? ` - ৳${Number(r.max_sale_amount).toFixed(0)}` : "+"}</td>
                  <td className="px-3 py-2 text-center text-[10px]">
                    {r.starts_at || r.ends_at ? (
                      <span className="text-amber-700">{fmtDate(r.starts_at) || "—"} → {fmtDate(r.ends_at) || "∞"}</span>
                    ) : <span className="text-muted-foreground">—</span>}
                  </td>
                  <td className="px-3 py-2 text-center text-xs">{r.priority}</td>
                  <td className="px-3 py-2 text-center">
                    <button onClick={() => toggleRule.mutate(r)} className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] ${r.is_active ? "bg-green-500/15 text-green-700" : "bg-muted text-muted-foreground"}`}>
                      <Power className="h-3 w-3" />{r.is_active ? (isBn ? "চালু" : "Active") : (isBn ? "বন্ধ" : "Inactive")}
                    </button>
                  </td>
                  <td className="px-3 py-2 text-right">
                    <div className="inline-flex gap-1">
                      <button onClick={() => { setEditRule(r); setShowForm(true); }} className="p-1.5 rounded hover:bg-accent"><Pencil className="h-3.5 w-3.5" /></button>
                      <button onClick={() => setDeleteRule(r)} className="p-1.5 rounded hover:bg-destructive/10 text-destructive"><Trash2 className="h-3.5 w-3.5" /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showForm && (
        <RuleModal isBn={isBn} initial={editRule} categories={categories as any} products={products as any} onClose={() => { setShowForm(false); setEditRule(null); }} onSubmit={(r) => upsertRule.mutate(r)} pending={upsertRule.isPending} />
      )}
      {deleteRule && (
        <Modal onClose={() => setDeleteRule(null)}>
          <h2 className="text-lg font-semibold mb-2">{isBn ? "রুল মুছবেন?" : "Delete rule?"}</h2>
          <p className="text-sm text-muted-foreground mb-4">{deleteRule.name}</p>
          <div className="flex justify-end gap-2">
            <button onClick={() => setDeleteRule(null)} className="rounded-lg border border-border px-3 py-2 text-sm">{isBn ? "বাতিল" : "Cancel"}</button>
            <button onClick={() => delRule.mutate()} disabled={delRule.isPending} className="rounded-lg bg-destructive text-destructive-foreground px-3 py-2 text-sm">{delRule.isPending ? "..." : (isBn ? "ডিলিট" : "Delete")}</button>
          </div>
        </Modal>
      )}
    </PageLayout>
  );
}

function Modal({ children, onClose }: { children: React.ReactNode; onClose: () => void }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto" onClick={onClose}>
      <div className="w-full max-w-lg rounded-2xl bg-card border border-border p-6 shadow-xl my-8" onClick={(e) => e.stopPropagation()}>{children}</div>
    </div>
  );
}

function RuleModal({ isBn, initial, categories, products, onClose, onSubmit, pending }: {
  isBn: boolean;
  initial: Rule | null;
  categories: { id: string; name: string; name_bn: string }[];
  products: { id: string; name: string; name_bn: string }[];
  onClose: () => void;
  onSubmit: (r: Partial<Rule>) => void;
  pending: boolean;
}) {
  const [name, setName] = useState(initial?.name || "");
  const [type, setType] = useState(initial?.commission_type || "percentage");
  const [value, setValue] = useState<number>(initial?.commission_value ? Number(initial.commission_value) : 0);
  const [minSale, setMinSale] = useState<number>(initial?.min_sale_amount ? Number(initial.min_sale_amount) : 0);
  const [maxSale, setMaxSale] = useState<string>(initial?.max_sale_amount ? String(initial.max_sale_amount) : "");
  const [priority, setPriority] = useState<number>(initial?.priority ?? 0);
  const [active, setActive] = useState<boolean>(initial?.is_active ?? true);
  const [note, setNote] = useState(initial?.note || "");
  const [level, setLevel] = useState<number>(initial?.level ?? 1);
  const [categoryId, setCategoryId] = useState<string>(initial?.category_id || "");
  const [productId, setProductId] = useState<string>(initial?.product_id || "");
  const toLocal = (d?: string | null) => d ? new Date(d).toISOString().slice(0, 10) : "";
  const [startsAt, setStartsAt] = useState<string>(toLocal(initial?.starts_at));
  const [endsAt, setEndsAt] = useState<string>(toLocal(initial?.ends_at));

  return (
    <Modal onClose={onClose}>
      <h2 className="text-lg font-semibold mb-4">{initial ? (isBn ? "রুল এডিট" : "Edit Rule") : (isBn ? "নতুন রুল" : "New Rule")}</h2>
      <div className="space-y-3">
        <div>
          <label className="text-xs text-muted-foreground">{isBn ? "নাম" : "Name"}</label>
          <input value={name} onChange={(e) => setName(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
        </div>
        <div className="grid grid-cols-3 gap-3">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "লেভেল" : "Level"}</label>
            <select value={level} onChange={(e) => setLevel(parseInt(e.target.value))} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value={1}>L1 — {isBn ? "সরাসরি" : "Direct"}</option>
              <option value={2}>L2 — {isBn ? "২য় স্তর" : "Tier 2"}</option>
              <option value={3}>L3 — {isBn ? "৩য় স্তর" : "Tier 3"}</option>
            </select>
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "ধরন" : "Type"}</label>
            <select value={type} onChange={(e) => setType(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value="percentage">{isBn ? "শতাংশ (%)" : "Percentage (%)"}</option>
              <option value="fixed">{isBn ? "নির্দিষ্ট" : "Fixed"}</option>
            </select>
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "মান" : "Value"}</label>
            <input type="number" step="0.01" value={value || ""} onChange={(e) => setValue(parseFloat(e.target.value) || 0)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "ক্যাটাগরি (ঐচ্ছিক)" : "Category (optional)"}</label>
            <select value={categoryId} onChange={(e) => setCategoryId(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value="">{isBn ? "— সব —" : "— All —"}</option>
              {categories.map((c) => <option key={c.id} value={c.id}>{isBn ? (c.name_bn || c.name) : c.name}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "প্রোডাক্ট (ঐচ্ছিক)" : "Product (optional)"}</label>
            <select value={productId} onChange={(e) => setProductId(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm">
              <option value="">{isBn ? "— সব —" : "— All —"}</option>
              {products.map((p) => <option key={p.id} value={p.id}>{isBn ? (p.name_bn || p.name) : p.name}</option>)}
            </select>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "মিন সেল (৳)" : "Min Sale (৳)"}</label>
            <input type="number" value={minSale || ""} onChange={(e) => setMinSale(parseFloat(e.target.value) || 0)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "ম্যাক্স সেল (৳)" : "Max Sale (৳)"}</label>
            <input type="number" value={maxSale} onChange={(e) => setMaxSale(e.target.value)} placeholder={isBn ? "ঐচ্ছিক" : "Optional"} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "শুরু তারিখ (ঐচ্ছিক)" : "Start Date (optional)"}</label>
            <input type="date" value={startsAt} onChange={(e) => setStartsAt(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "শেষ তারিখ (ঐচ্ছিক)" : "End Date (optional)"}</label>
            <input type="date" value={endsAt} onChange={(e) => setEndsAt(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="text-xs text-muted-foreground">{isBn ? "প্রায়োরিটি" : "Priority"}</label>
            <input type="number" value={priority} onChange={(e) => setPriority(parseInt(e.target.value) || 0)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div className="flex items-end">
            <label className="flex items-center gap-2 text-sm pb-2">
              <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />
              {isBn ? "চালু" : "Active"}
            </label>
          </div>
        </div>
        <div>
          <label className="text-xs text-muted-foreground">{isBn ? "নোট" : "Note"}</label>
          <input value={note} onChange={(e) => setNote(e.target.value)} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="rounded-lg border border-border px-3 py-2 text-sm">{isBn ? "বাতিল" : "Cancel"}</button>
          <button onClick={() => onSubmit({
            name, commission_type: type, commission_value: value, min_sale_amount: minSale,
            max_sale_amount: maxSale ? parseFloat(maxSale) : null, priority, is_active: active, note,
            level, category_id: categoryId || null, product_id: productId || null,
            starts_at: startsAt ? new Date(startsAt).toISOString() : null,
            ends_at: endsAt ? new Date(endsAt).toISOString() : null,
          })} disabled={pending || !name.trim()} className="rounded-lg bg-primary text-primary-foreground px-3 py-2 text-sm disabled:opacity-50">
            {pending ? "..." : (isBn ? "সংরক্ষণ" : "Save")}
          </button>
        </div>
      </div>
    </Modal>
  );
}
