import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { ArrowLeft, Loader2, Save, Search, Trash2, History } from "lucide-react";
import { useReceiptPrint } from "@/components/ReceiptPrint";
import { statusLabel, type SaleStatus } from "@/components/sales/sale-status";
import { useSaleStatusRules } from "@/hooks/use-sale-status-rules";

export const Route = createFileRoute("/_authenticated/sales/$saleId/edit")({
  head: () => ({ meta: [{ title: "Edit Sale Invoice — Niyamah ERP" }] }),
  component: EditSalePage,
});

type Item = {
  id?: string;
  product_id: string | null;
  name: string;
  name_bn: string;
  barcode: string;
  unit: string;
  quantity: number;
  unit_price: number;
  unit_discount: number;
  total: number;
  stock: number;
  original_qty: number; // 0 for newly added
};

function EditSalePage() {
  const { saleId } = Route.useParams();
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { user } = useAuth();
  const { printReceipt } = useReceiptPrint();
  const { getNext: nextStatuses } = useSaleStatusRules();

  // Header fields
  const [invoiceNo, setInvoiceNo] = useState("");
  const [saleDate, setSaleDate] = useState("");
  const [customerId, setCustomerId] = useState<string | null>(null);
  const [customerName, setCustomerName] = useState("");
  const [customerMobile, setCustomerMobile] = useState("");
  const [customerAddress, setCustomerAddress] = useState("");
  const [saleMan, setSaleMan] = useState("");
  const [branchId, setBranchId] = useState<string>("");
  const [paymentMethod, setPaymentMethod] = useState("cash");
  const [saleStatus, setSaleStatus] = useState<string>("completed");
  const [originalStatus, setOriginalStatus] = useState<string>("completed");
  const [paidAmount, setPaidAmount] = useState(0);
  const [discount, setDiscount] = useState(0);
  const [expense, setExpense] = useState(0);
  const [note, setNote] = useState("");
  const [items, setItems] = useState<Item[]>([]);
  const [originalSnapshot, setOriginalSnapshot] = useState<any>(null);
  const [loaded, setLoaded] = useState(false);

  // Customer search
  const [custQuery, setCustQuery] = useState("");
  const [custResults, setCustResults] = useState<any[]>([]);
  const [showCustDrop, setShowCustDrop] = useState(false);
  const custRef = useRef<HTMLDivElement>(null);

  // Product search
  const [prodQuery, setProdQuery] = useState("");
  const [prodResults, setProdResults] = useState<any[]>([]);
  const [showProdDrop, setShowProdDrop] = useState(false);
  const prodRef = useRef<HTMLDivElement>(null);

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

  const { data: editLogs = [] } = useQuery({
    queryKey: ["sale-edit-logs", saleId],
    queryFn: async () => {
      const { data } = await supabase
        .from("sale_edit_logs" as any)
        .select("*")
        .eq("sale_id", saleId)
        .order("created_at", { ascending: false });
      return (data as any[]) || [];
    },
  });

  // Load sale + items
  useEffect(() => {
    (async () => {
      const [{ data: sale, error }, { data: its }] = await Promise.all([
        supabase.from("sales" as any).select("*").eq("id", saleId).single(),
        supabase
          .from("sale_items" as any)
          .select("*, products(stock_quantity)")
          .eq("sale_id", saleId),
      ]);
      if (error || !sale) {
        toast.error(error?.message || "Not found");
        return;
      }
      const s = sale as any;
      setInvoiceNo(s.invoice_no);
      setSaleDate(s.sale_date || "");
      setCustomerId(s.customer_id);
      setCustomerName(s.customer_name || "");
      setCustomerMobile(s.customer_mobile || "");
      setCustomerAddress(s.customer_address || "");
      setSaleMan(s.sale_man || "");
      setBranchId(s.branch_id || "");
      setPaymentMethod(s.payment_method || "cash");
      setSaleStatus(s.sale_status || s.status || "completed");
      setOriginalStatus(s.sale_status || s.status || "completed");
      setPaidAmount(Number(s.paid_amount) || 0);
      setDiscount(Number(s.discount) || 0);
      setExpense(Number(s.expense) || 0);
      setNote(s.note || "");
      const itemsArr: Item[] = ((its as any[]) || []).map((it) => ({
        id: it.id,
        product_id: it.product_id,
        name: it.name || "",
        name_bn: it.name_bn || "",
        barcode: it.barcode || "",
        unit: it.unit || "",
        quantity: Number(it.quantity),
        unit_price: Number(it.unit_price),
        unit_discount: Number(it.unit_discount),
        total: Number(it.total),
        stock: Number(it.products?.stock_quantity) || 0,
        original_qty: Number(it.quantity),
      }));
      setItems(itemsArr);
      setOriginalSnapshot({
        sale: s,
        items: itemsArr.map((i) => ({ ...i })),
      });
      setLoaded(true);
    })();
  }, [saleId]);

  // Customer search
  useEffect(() => {
    if (custQuery.length < 2) {
      setCustResults([]);
      return;
    }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("customers")
        .select("*")
        .or(`name.ilike.%${custQuery}%,mobile.ilike.%${custQuery}%`)
        .limit(10);
      setCustResults((data as any[]) || []);
      setShowCustDrop(true);
    }, 300);
    return () => clearTimeout(t);
  }, [custQuery]);

  // Product search
  useEffect(() => {
    if (prodQuery.length < 2) {
      setProdResults([]);
      return;
    }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("products")
        .select("id, name, name_bn, sku, barcode, stock_quantity, retail_price, wholesale_price, unit")
        .eq("is_deleted", false)
        .or(`name.ilike.%${prodQuery}%,sku.ilike.%${prodQuery}%,barcode.ilike.%${prodQuery}%`)
        .limit(10);
      setProdResults((data as any[]) || []);
      setShowProdDrop(true);
    }, 300);
    return () => clearTimeout(t);
  }, [prodQuery]);

  useEffect(() => {
    const h = (e: MouseEvent) => {
      if (custRef.current && !custRef.current.contains(e.target as Node)) setShowCustDrop(false);
      if (prodRef.current && !prodRef.current.contains(e.target as Node)) setShowProdDrop(false);
    };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);

  const subtotal = useMemo(
    () => items.reduce((s, i) => s + i.unit_price * i.quantity, 0),
    [items],
  );
  const totalItemDiscount = useMemo(
    () => items.reduce((s, i) => s + i.unit_discount * i.quantity, 0),
    [items],
  );
  const totalAmount = Math.max(0, subtotal - totalItemDiscount - discount + expense);
  const dueAmount = Math.max(0, totalAmount - paidAmount);

  const addProduct = (p: any) => {
    const existing = items.find((i) => i.product_id === p.id);
    const price = Number(p.retail_price) || 0;
    if (existing) {
      setItems(
        items.map((i) =>
          i.product_id === p.id
            ? { ...i, quantity: i.quantity + 1, total: (i.quantity + 1) * i.unit_price - i.unit_discount * (i.quantity + 1) }
            : i,
        ),
      );
    } else {
      setItems([
        ...items,
        {
          product_id: p.id,
          name: p.name,
          name_bn: p.name_bn || "",
          barcode: p.barcode || "",
          unit: p.unit || "pcs",
          quantity: 1,
          unit_price: price,
          unit_discount: 0,
          total: price,
          stock: Number(p.stock_quantity) || 0,
          original_qty: 0,
        },
      ]);
    }
    setProdQuery("");
    setShowProdDrop(false);
  };

  const updateItem = (idx: number, field: "quantity" | "unit_price" | "unit_discount" | "unit", value: any) => {
    setItems(
      items.map((it, i) => {
        if (i !== idx) return it;
        const u: Item = { ...it, [field]: field === "unit" ? value : Number(value) || 0 };
        u.total = u.quantity * u.unit_price - u.quantity * u.unit_discount;
        return u;
      }),
    );
  };

  const removeItem = (idx: number) => setItems(items.filter((_, i) => i !== idx));

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (items.length === 0) throw new Error(isBn ? "অন্তত একটি পণ্য রাখুন" : "Keep at least one item");

      // Day-close lock: block edits when sale_date is locked in daily_cash_closings
      const origDate = (originalSnapshot as any)?.sale?.sale_date;
      const checkDates = Array.from(new Set([origDate, saleDate].filter(Boolean))) as string[];
      if (checkDates.length > 0) {
        const { data: locks } = await supabase
          .from("daily_cash_closings")
          .select("closing_date, branch_id, is_locked")
          .in("closing_date", checkDates)
          .eq("is_locked", true);
        const matched = (locks || []).find((l: any) =>
          !l.branch_id || !branchId || l.branch_id === branchId
        );
        if (matched) {
          throw new Error(
            isBn
              ? `${(matched as any).closing_date} তারিখটি ক্যাশ ক্লোজিংয়ে লক করা — সেল এডিট করা যাবে না`
              : `${(matched as any).closing_date} is locked in daily cash closing — sale edit blocked`,
          );
        }
      }

      // Status transition validation
      if (saleStatus !== originalStatus) {
        const allowed = nextStatuses(originalStatus as SaleStatus);
        if (!allowed.includes(saleStatus as SaleStatus)) {
          throw new Error(
            isBn
              ? `স্ট্যাটাস পরিবর্তন অনুমোদিত নয়: ${statusLabel(originalStatus, true)} → ${statusLabel(saleStatus, true)}`
              : `Status transition not allowed: ${statusLabel(originalStatus, false)} → ${statusLabel(saleStatus, false)}`,
          );
        }
      }

      // Stock validation: any qty increase or new item must fit available stock
      for (const it of items) {
        const delta = it.quantity - it.original_qty;
        if (delta > 0 && it.product_id && delta > it.stock) {
          throw new Error(
            isBn
              ? `${it.name}: পর্যাপ্ত স্টক নেই (অতিরিক্ত প্রয়োজন: ${delta}, স্টক: ${it.stock})`
              : `${it.name}: insufficient stock (need ${delta} more, have ${it.stock})`,
          );
        }
      }

      // Build product delta map (positive = restore to stock, negative = deduct)
      const deltaMap = new Map<string, number>();
      for (const it of items) {
        if (!it.product_id) continue;
        const prev = deltaMap.get(it.product_id) || 0;
        deltaMap.set(it.product_id, prev + (it.original_qty - it.quantity));
      }
      // Removed items
      const remainingIds = new Set(items.filter((i) => i.id).map((i) => i.id));
      const { data: oldItems } = await supabase
        .from("sale_items" as any)
        .select("id, product_id, quantity")
        .eq("sale_id", saleId);
      for (const oi of (oldItems as any[]) || []) {
        if (!remainingIds.has(oi.id) && oi.product_id) {
          const prev = deltaMap.get(oi.product_id) || 0;
          deltaMap.set(oi.product_id, prev + Number(oi.quantity)); // restore
        }
      }

      // Apply stock deltas
      for (const [pid, delta] of deltaMap.entries()) {
        if (delta === 0) continue;
        const { data: prod } = await supabase
          .from("products")
          .select("stock_quantity")
          .eq("id", pid)
          .single();
        const cur = Number((prod as any)?.stock_quantity) || 0;
        await supabase
          .from("products")
          .update({ stock_quantity: Math.max(0, cur + delta) } as any)
          .eq("id", pid);
      }

      // Replace items
      const { error: delErr } = await supabase
        .from("sale_items" as any)
        .delete()
        .eq("sale_id", saleId);
      if (delErr) throw delErr;

      const rows = items.map((it) => ({
        sale_id: saleId,
        product_id: it.product_id,
        name: it.name,
        name_bn: it.name_bn,
        barcode: it.barcode,
        unit: it.unit,
        quantity: it.quantity,
        unit_price: it.unit_price,
        unit_discount: it.unit_discount,
        total: it.total,
      }));
      const { error: insErr } = await supabase.from("sale_items" as any).insert(rows);
      if (insErr) throw insErr;

      // Update header
      const newHeader = {
        customer_id: customerId,
        customer_name: customerName,
        customer_mobile: customerMobile,
        customer_address: customerAddress,
        sale_man: saleMan,
        sale_date: saleDate,
        branch_id: branchId || null,
        subtotal,
        discount,
        expense,
        total_amount: totalAmount,
        paid_amount: paidAmount,
        due_amount: dueAmount,
        payment_method: paymentMethod,
        sale_status: saleStatus,
        delivery_status:
          saleStatus === "delivered" || saleStatus === "completed"
            ? "delivered"
            : saleStatus === "partial_delivered"
              ? "partial"
              : "pending",
        note,
        is_edited: true,
        edited_by: user?.id ?? null,
        edited_at: new Date().toISOString(),
        edit_count: (Number(originalSnapshot?.sale?.edit_count) || 0) + 1,
      };
      const { error: updErr } = await supabase
        .from("sales" as any)
        .update(newHeader as any)
        .eq("id", saleId);
      if (updErr) throw updErr;

      // Compute changed fields
      const oldSale = originalSnapshot?.sale || {};
      const changedFields: string[] = [];
      const compareKeys = [
        "customer_id", "customer_name", "customer_mobile", "customer_address", "sale_man",
        "sale_date", "branch_id", "subtotal", "discount", "expense", "total_amount",
        "paid_amount", "due_amount", "payment_method", "sale_status", "delivery_status", "note",
      ];
      for (const k of compareKeys) {
        if (String((oldSale as any)[k] ?? "") !== String((newHeader as any)[k] ?? "")) {
          changedFields.push(k);
        }
      }
      // Items changed?
      const oldItemsKey = (originalSnapshot?.items || [])
        .map((i: Item) => `${i.product_id}:${i.quantity}:${i.unit_price}:${i.unit_discount}`)
        .sort()
        .join("|");
      const newItemsKey = items
        .map((i) => `${i.product_id}:${i.quantity}:${i.unit_price}:${i.unit_discount}`)
        .sort()
        .join("|");
      if (oldItemsKey !== newItemsKey) changedFields.push("items");

      // Insert audit log
      await supabase.from("sale_edit_logs" as any).insert({
        sale_id: saleId,
        old_data: {
          ...oldSale,
          items: originalSnapshot?.items || [],
        },
        new_data: {
          ...newHeader,
          items,
        },
        changed_fields: changedFields,
        edited_by: user?.id ?? null,
      });
    },
    onSuccess: () => {
      toast.success(isBn ? "ইনভয়েস আপডেট হয়েছে" : "Invoice updated");
      qc.invalidateQueries({ queryKey: ["sales-list"] });
      qc.invalidateQueries({ queryKey: ["sale-edit-logs", saleId] });
      navigate({ to: "/sales" });
    },
    onError: (e: any) => toast.error(e.message),
  });

  const handlePrint = () => {
    printReceipt({
      invoiceNo,
      date: new Date(saleDate).toLocaleDateString(isBn ? "bn-BD" : "en-GB"),
      customer: customerName,
      phone: customerMobile,
      address: customerAddress,
      saleMan,
      items: items.map((it) => ({
        name: isBn ? it.name_bn || it.name : it.name,
        code: it.barcode || "",
        quantity: it.quantity,
        unit: it.unit,
        unitPrice: it.unit_price,
        discount: it.unit_discount * it.quantity,
      })),
      subTotal: subtotal,
      discount: discount + totalItemDiscount,
      expense,
      grandTotal: totalAmount,
      paid: paidAmount,
      due: dueAmount,
    });
  };

  const inputCls =
    "w-full rounded-lg border border-border bg-card px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/40";

  if (!loaded)
    return (
      <PageLayout>
        <div className="p-8 text-center text-muted-foreground">Loading...</div>
      </PageLayout>
    );

  return (
    <PageLayout>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <Link to="/sales" className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground">
            <ArrowLeft className="h-4 w-4" />
            {isBn ? "ফিরে যান" : "Back"}
          </Link>
          <div>
            <h1 className="text-xl font-bold text-foreground">
              {isBn ? "ইনভয়েস এডিট" : "Edit Invoice"}{" "}
              <span className="text-sm font-mono text-muted-foreground ml-2">{invoiceNo}</span>
            </h1>
            <p className="text-xs text-orange-600 dark:text-orange-400 mt-0.5">
              {isBn
                ? "⚠ পরিমাণ পরিবর্তনে স্টক স্বয়ংক্রিয়ভাবে সমন্বয় হবে"
                : "⚠ Quantity changes will auto-adjust product stock"}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={handlePrint}
            className="rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-muted"
          >
            {isBn ? "প্রিন্ট" : "Print"}
          </button>
          <button
            disabled={saveMutation.isPending}
            onClick={() => saveMutation.mutate()}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-50"
          >
            {saveMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            {isBn ? "আপডেট" : "Update"}
          </button>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2 space-y-6">
          {/* Customer */}
          <div className="rounded-xl border border-border bg-card p-5">
            <h3 className="text-sm font-semibold mb-3">{isBn ? "গ্রাহক" : "Customer"}</h3>
            <div ref={custRef} className="relative mb-3">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <input
                className={`${inputCls} pl-9`}
                placeholder={isBn ? "নাম / মোবাইল দিয়ে খুঁজুন" : "Search name / mobile"}
                value={custQuery}
                onChange={(e) => setCustQuery(e.target.value)}
              />
              {showCustDrop && custResults.length > 0 && (
                <div className="absolute z-30 mt-1 w-full rounded-lg border border-border bg-popover shadow-lg max-h-48 overflow-y-auto">
                  {custResults.map((c: any) => (
                    <button
                      key={c.id}
                      className="w-full text-left px-4 py-2 text-sm hover:bg-accent"
                      onClick={() => {
                        setCustomerId(c.id);
                        setCustomerName(c.name);
                        setCustomerMobile(c.mobile || "");
                        setCustomerAddress(c.address || "");
                        setShowCustDrop(false);
                        setCustQuery("");
                      }}
                    >
                      <div className="font-medium">{c.name}</div>
                      <div className="text-xs text-muted-foreground">{c.mobile}</div>
                    </button>
                  ))}
                </div>
              )}
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground">{isBn ? "নাম" : "Name"}</label>
                <input className={inputCls} value={customerName} onChange={(e) => setCustomerName(e.target.value)} />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">{isBn ? "মোবাইল" : "Mobile"}</label>
                <input className={inputCls} value={customerMobile} onChange={(e) => setCustomerMobile(e.target.value)} />
              </div>
              <div className="col-span-2">
                <label className="text-xs font-medium text-muted-foreground">{isBn ? "ঠিকানা" : "Address"}</label>
                <input className={inputCls} value={customerAddress} onChange={(e) => setCustomerAddress(e.target.value)} />
              </div>
            </div>
          </div>

          {/* Items */}
          <div className="rounded-xl border border-border bg-card p-5">
            <h3 className="text-sm font-semibold mb-3">{isBn ? "পণ্য" : "Items"}</h3>
            <div ref={prodRef} className="relative mb-4">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <input
                className={`${inputCls} pl-9`}
                placeholder={isBn ? "পণ্য যোগ করুন" : "Add product"}
                value={prodQuery}
                onChange={(e) => setProdQuery(e.target.value)}
              />
              {showProdDrop && prodResults.length > 0 && (
                <div className="absolute z-30 mt-1 w-full rounded-lg border border-border bg-popover shadow-lg max-h-48 overflow-y-auto">
                  {prodResults.map((p: any) => (
                    <button
                      key={p.id}
                      className="w-full text-left px-4 py-2 text-sm hover:bg-accent"
                      onClick={() => addProduct(p)}
                    >
                      <div className="font-medium">{p.name}</div>
                      <div className="text-xs text-muted-foreground">
                        SKU: {p.sku} · {isBn ? "স্টক" : "Stock"}: {p.stock_quantity} · ৳{p.retail_price}
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>

            {items.length > 0 && (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-border text-left">
                      <th className="pb-2 font-medium">{isBn ? "পণ্য" : "Product"}</th>
                      <th className="pb-2 font-medium w-20">{isBn ? "পরিমাণ" : "Qty"}</th>
                      <th className="pb-2 font-medium w-20">{isBn ? "ইউনিট" : "Unit"}</th>
                      <th className="pb-2 font-medium w-28">{isBn ? "মূল্য" : "Price"}</th>
                      <th className="pb-2 font-medium w-24">{isBn ? "ডিসকাউন্ট" : "Disc"}</th>
                      <th className="pb-2 font-medium w-28 text-right">{isBn ? "মোট" : "Total"}</th>
                      <th className="pb-2 w-10"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {items.map((it, idx) => (
                      <tr key={`${it.product_id}-${idx}`} className="border-b border-border/30">
                        <td className="py-2">
                          <div>{isBn ? it.name_bn || it.name : it.name}</div>
                          <div className="text-[11px] text-muted-foreground">
                            {isBn ? "স্টক" : "Stock"}: {it.stock} · {isBn ? "মূল" : "Original"}: {it.original_qty}
                          </div>
                        </td>
                        <td className="py-2">
                          <input
                            type="number"
                            min={1}
                            className="w-16 rounded border border-border bg-background px-2 py-1 text-sm"
                            value={it.quantity}
                            onChange={(e) => updateItem(idx, "quantity", e.target.value)}
                          />
                        </td>
                        <td className="py-2">
                          <input
                            className="w-16 rounded border border-border bg-background px-2 py-1 text-sm"
                            value={it.unit}
                            onChange={(e) => updateItem(idx, "unit", e.target.value)}
                          />
                        </td>
                        <td className="py-2">
                          <input
                            type="number"
                            min={0}
                            className="w-24 rounded border border-border bg-background px-2 py-1 text-sm"
                            value={it.unit_price}
                            onChange={(e) => updateItem(idx, "unit_price", e.target.value)}
                          />
                        </td>
                        <td className="py-2">
                          <input
                            type="number"
                            min={0}
                            className="w-20 rounded border border-border bg-background px-2 py-1 text-sm"
                            value={it.unit_discount}
                            onChange={(e) => updateItem(idx, "unit_discount", e.target.value)}
                          />
                        </td>
                        <td className="py-2 text-right font-medium">৳{it.total.toLocaleString()}</td>
                        <td className="py-2">
                          <button onClick={() => removeItem(idx)} className="text-red-500 hover:text-red-700">
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Edit history */}
          <div className="rounded-xl border border-border bg-card p-5">
            <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <History className="h-4 w-4" />
              {isBn ? "এডিট হিস্ট্রি" : "Edit History"}{" "}
              <span className="text-xs text-muted-foreground">({editLogs.length})</span>
            </h3>
            {editLogs.length === 0 ? (
              <p className="text-xs text-muted-foreground">{isBn ? "কোনো এডিট নেই" : "No edits yet"}</p>
            ) : (
              <div className="space-y-2 max-h-64 overflow-y-auto">
                {editLogs.map((log: any) => (
                  <div key={log.id} className="rounded-lg border border-border/50 p-3 text-xs">
                    <div className="flex items-center justify-between mb-1">
                      <span className="font-mono text-muted-foreground">
                        {new Date(log.created_at).toLocaleString(isBn ? "bn-BD" : "en-GB")}
                      </span>
                      <span className="text-muted-foreground">{log.edited_by ? log.edited_by.slice(0, 8) : "—"}</span>
                    </div>
                    <div className="flex flex-wrap gap-1">
                      {(log.changed_fields || []).map((f: string) => (
                        <span key={f} className="rounded-full bg-secondary px-2 py-0.5 text-[10px]">
                          {f}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-4">
          <div className="rounded-xl border border-border bg-card p-5 space-y-3">
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "তারিখ" : "Date"}</label>
              <input type="date" className={inputCls} value={saleDate} onChange={(e) => setSaleDate(e.target.value)} />
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "শাখা" : "Branch"}</label>
              <select className={inputCls} value={branchId} onChange={(e) => setBranchId(e.target.value)}>
                <option value="">—</option>
                {branches.map((b: any) => (
                  <option key={b.id} value={b.id}>
                    {b.name}
                  </option>
                ))}
              </select>
            </div>
            <SaleStatusSelector
              originalStatus={originalStatus}
              saleStatus={saleStatus}
              setSaleStatus={setSaleStatus}
              nextStatuses={nextStatuses}
              isBn={isBn}
              inputCls={inputCls}
            />
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "SR / DSR" : "SR / DSR"}</label>
              <input className={inputCls} value={saleMan} onChange={(e) => setSaleMan(e.target.value)} />
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "নোট" : "Note"}</label>
              <textarea className={inputCls} rows={2} value={note} onChange={(e) => setNote(e.target.value)} />
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card p-5 space-y-3">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{isBn ? "সাবটোটাল" : "Subtotal"}</span>
              <span className="font-medium">৳{subtotal.toLocaleString()}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{isBn ? "আইটেম ডিসকাউন্ট" : "Item Discount"}</span>
              <span className="font-medium">-৳{totalItemDiscount.toLocaleString()}</span>
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "অতিরিক্ত ছাড়" : "Extra Discount"}</label>
              <input
                type="number"
                min={0}
                className={inputCls}
                value={discount}
                onChange={(e) => setDiscount(Number(e.target.value) || 0)}
              />
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "খরচ" : "Expense"}</label>
              <input
                type="number"
                min={0}
                className={inputCls}
                value={expense}
                onChange={(e) => setExpense(Number(e.target.value) || 0)}
              />
            </div>
            <div className="flex justify-between text-sm pt-2 border-t border-border">
              <span className="font-semibold">{isBn ? "মোট" : "Total"}</span>
              <span className="font-bold text-primary">৳{totalAmount.toLocaleString()}</span>
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "পরিশোধিত" : "Paid"}</label>
              <input
                type="number"
                min={0}
                className={inputCls}
                value={paidAmount}
                onChange={(e) => setPaidAmount(Number(e.target.value) || 0)}
              />
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "পেমেন্ট মাধ্যম" : "Payment Method"}</label>
              <select
                className={inputCls}
                value={paymentMethod}
                onChange={(e) => setPaymentMethod(e.target.value)}
              >
                <option value="cash">{isBn ? "নগদ" : "Cash"}</option>
                <option value="bkash">bKash</option>
                <option value="nagad">Nagad</option>
                <option value="bank">{isBn ? "ব্যাংক" : "Bank"}</option>
              </select>
            </div>
            <div className="flex justify-between text-sm pt-2 border-t border-border">
              <span className="text-muted-foreground">{isBn ? "বকেয়া" : "Due"}</span>
              <span className="font-semibold text-orange-600">৳{dueAmount.toLocaleString()}</span>
            </div>
          </div>
        </div>
      </div>
      <SaleStatusHistory saleId={saleId} isBn={isBn} />
    </PageLayout>
  );
}

function SaleStatusSelector({
  originalStatus,
  saleStatus,
  setSaleStatus,
  nextStatuses,
  isBn,
  inputCls,
}: {
  originalStatus: string;
  saleStatus: string;
  setSaleStatus: (v: string) => void;
  nextStatuses: (s: SaleStatus) => SaleStatus[];
  isBn: boolean;
  inputCls: string;
}) {
  const allowed = nextStatuses(originalStatus as SaleStatus);
  const opts = Array.from(new Set<string>([originalStatus, ...allowed]));
  const isTerminal = allowed.length === 0;
  return (
    <div>
      <label className="text-xs font-medium text-muted-foreground">{isBn ? "সেল স্ট্যাটাস" : "Sale Status"}</label>
      <select
        className={inputCls}
        value={saleStatus}
        onChange={(e) => setSaleStatus(e.target.value)}
        disabled={isTerminal}
      >
        {opts.map((s) => (
          <option key={s} value={s}>{statusLabel(s, isBn)}</option>
        ))}
      </select>
      <p className="text-[11px] text-muted-foreground mt-1">
        {isTerminal
          ? (isBn ? "এই স্ট্যাটাস থেকে পরিবর্তন সম্ভব নয়" : "No transitions allowed from this status")
          : (isBn
              ? `অনুমোদিত: ${allowed.map((a: SaleStatus) => statusLabel(a, true)).join(", ")}`
              : `Allowed: ${allowed.map((a: SaleStatus) => statusLabel(a, false)).join(", ")}`)}
      </p>
    </div>
  );
}

function SaleStatusHistory({ saleId, isBn }: { saleId: string; isBn: boolean }) {
  const { data: logs = [] } = useQuery({
    queryKey: ["sale-status-logs", saleId],
    queryFn: async () => {
      const { data } = await supabase
        .from("sale_status_logs" as any)
        .select("*")
        .eq("sale_id", saleId)
        .order("created_at", { ascending: false })
        .limit(50);
      return (data as any[]) || [];
    },
  });
  if (!logs.length) return null;
  return (
    <div className="mt-6 rounded-xl border border-border bg-card p-5">
      <div className="text-sm font-semibold mb-3">{isBn ? "স্ট্যাটাস ইতিহাস" : "Status History"}</div>
      <div className="space-y-2">
        {logs.map((l: any) => (
          <div key={l.id} className="flex items-center justify-between text-xs border-b border-border pb-2 last:border-0">
            <div>
              <span className="font-medium text-foreground">{l.change_type}</span>
              <span className="mx-2 text-muted-foreground">{l.old_value || "—"} → {l.new_value || "—"}</span>
            </div>
            <span className="text-muted-foreground">{new Date(l.created_at).toLocaleString(isBn ? "bn-BD" : "en-GB")}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

