import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/use-auth";
import { useState, useRef, useEffect, useMemo } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  Loader2,
  Search,
  Trash2,
  Plus,
  Minus,
  Truck,
  Package,
  Receipt,
  Wallet,
  Calendar,
  FileText,
  Save,
  X,
  CheckCircle2,
  AlertCircle,
  Phone,
  MapPin,
  Hash,
  ShoppingCart,
} from "lucide-react";

export const Route = createFileRoute("/_authenticated/purchases/add")({
  head: () => ({
    meta: [
      { title: "নতুন ক্রয় — Niyamah ERP" },
      { name: "description", content: "Add new purchase entry" },
    ],
  }),
  component: AddPurchasePage,
});

type UnitOption = {
  unit_name: string;
  unit_name_bn: string;
  conversion_factor: number;
  purchase_price: number;
};

type PurchaseItem = {
  product_id: string;
  product_name: string;
  base_unit: string;
  quantity: number;
  purchase_price: number;
  total: number;
  selected_unit: string;
  conversion_factor: number;
  available_units: UnitOption[];
  current_stock: number;
};

function AddPurchasePage() {
  const { tr, lang } = useLanguage();
  const { user } = useAuth();
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  // Supplier search
  const [supplierQuery, setSupplierQuery] = useState("");
  const [supplierResults, setSupplierResults] = useState<any[]>([]);
  const [selectedSupplier, setSelectedSupplier] = useState<any>(null);
  const [showSupplierDrop, setShowSupplierDrop] = useState(false);
  const [supplierSearching, setSupplierSearching] = useState(false);
  const supplierRef = useRef<HTMLDivElement>(null);

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

  // Items + payment
  const [items, setItems] = useState<PurchaseItem[]>([]);
  const [discount, setDiscount] = useState<number>(0);
  const [transportCost, setTransportCost] = useState<number>(0);
  const [laborCost, setLaborCost] = useState<number>(0);
  const [paidAmount, setPaidAmount] = useState<number>(0);
  const [paymentMethod, setPaymentMethod] = useState("cash");
  const [purchaseDate, setPurchaseDate] = useState(
    new Date().toISOString().split("T")[0],
  );
  const [invoiceNo, setInvoiceNo] = useState("");
  const [note, setNote] = useState("");
  const [touched, setTouched] = useState(false);

  const subtotal = useMemo(
    () => items.reduce((sum, i) => sum + i.total, 0),
    [items],
  );
  const totalAmount = Math.max(0, subtotal - discount + transportCost + laborCost);
  const dueAmount = totalAmount - paidAmount;
  const totalQty = useMemo(
    () => items.reduce((s, i) => s + i.quantity, 0),
    [items],
  );


  // --- Supplier search ---
  useEffect(() => {
    if (supplierQuery.length < 2) {
      setSupplierResults([]);
      setSupplierSearching(false);
      return;
    }
    setSupplierSearching(true);
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("suppliers" as any)
        .select("*")
        .or(
          `name.ilike.%${supplierQuery}%,name_bn.ilike.%${supplierQuery}%,mobile.ilike.%${supplierQuery}%`,
        )
        .limit(10);
      setSupplierResults((data as any[]) || []);
      setShowSupplierDrop(true);
      setSupplierSearching(false);
    }, 300);
    return () => clearTimeout(t);
  }, [supplierQuery]);

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

  // Click outside
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (supplierRef.current && !supplierRef.current.contains(e.target as Node))
        setShowSupplierDrop(false);
      if (prodRef.current && !prodRef.current.contains(e.target as Node))
        setShowProdDrop(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  // Auto-focus product search after supplier selected
  useEffect(() => {
    if (selectedSupplier && items.length === 0) {
      setTimeout(() => prodInputRef.current?.focus(), 150);
    }
  }, [selectedSupplier]);

  const addProduct = async (product: any) => {
    const existing = items.find((i) => i.product_id === product.id);
    if (existing) {
      setItems(
        items.map((i) =>
          i.product_id === product.id
            ? {
                ...i,
                quantity: i.quantity + 1,
                total: (i.quantity + 1) * i.purchase_price,
              }
            : i,
        ),
      );
    } else {
      const { data: units } = await supabase
        .from("product_units")
        .select("unit_name, unit_name_bn, conversion_factor, purchase_price")
        .eq("product_id", product.id)
        .eq("is_active", true);
      const baseUnit = product.unit || "pcs";
      const available: UnitOption[] = [
        {
          unit_name: baseUnit,
          unit_name_bn: baseUnit,
          conversion_factor: 1,
          purchase_price: Number(product.purchase_price) || 0,
        },
        ...((units as any[]) || []).map((u) => ({
          unit_name: u.unit_name,
          unit_name_bn: u.unit_name_bn || u.unit_name,
          conversion_factor: Number(u.conversion_factor),
          purchase_price: Number(u.purchase_price) || 0,
        })),
      ];
      setItems([
        ...items,
        {
          product_id: product.id,
          product_name: product.name,
          base_unit: baseUnit,
          quantity: 1,
          purchase_price: Number(product.purchase_price) || 0,
          total: Number(product.purchase_price) || 0,
          selected_unit: baseUnit,
          conversion_factor: 1,
          available_units: available,
          current_stock: Number(product.stock_quantity) || 0,
        },
      ]);
    }
    setProdQuery("");
    setShowProdDrop(false);
    setTimeout(() => prodInputRef.current?.focus(), 50);
  };

  const updateItem = (
    idx: number,
    field: "quantity" | "purchase_price",
    value: number,
  ) => {
    setItems(
      items.map((item, i) => {
        if (i !== idx) return item;
        const updated = { ...item, [field]: Math.max(0, value) };
        updated.total = updated.quantity * updated.purchase_price;
        return updated;
      }),
    );
  };

  const stepQty = (idx: number, delta: number) => {
    setItems(
      items.map((item, i) => {
        if (i !== idx) return item;
        const q = Math.max(1, item.quantity + delta);
        return { ...item, quantity: q, total: q * item.purchase_price };
      }),
    );
  };

  const updateItemUnit = (idx: number, unitName: string) => {
    setItems(
      items.map((item, i) => {
        if (i !== idx) return item;
        const u = item.available_units.find((x) => x.unit_name === unitName);
        if (!u) return item;
        const newPrice = u.purchase_price || item.purchase_price;
        return {
          ...item,
          selected_unit: unitName,
          conversion_factor: u.conversion_factor,
          purchase_price: newPrice,
          total: item.quantity * newPrice,
        };
      }),
    );
  };

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

  const setPayFull = () => setPaidAmount(totalAmount);
  const setPayHalf = () => setPaidAmount(Math.round(totalAmount / 2));
  const setPayNone = () => setPaidAmount(0);

  const validate = () => {
    if (!selectedSupplier) {
      toast.error(
        lang === "bn"
          ? "অনুগ্রহ করে সরবরাহকারী নির্বাচন করুন"
          : "Please select a supplier",
      );
      return false;
    }
    if (items.length === 0) {
      toast.error(
        lang === "bn"
          ? "অন্তত একটি পণ্য যোগ করুন"
          : "Please add at least one product",
      );
      return false;
    }
    const bad = items.find((i) => i.quantity <= 0 || i.purchase_price < 0);
    if (bad) {
      toast.error(
        lang === "bn"
          ? "সব পণ্যের সঠিক পরিমাণ ও মূল্য দিন"
          : "Enter valid quantity & price for all products",
      );
      return false;
    }
    if (paidAmount > totalAmount) {
      toast.error(
        lang === "bn"
          ? "প্রদত্ত টাকা মোটের চেয়ে বেশি হতে পারে না"
          : "Paid cannot exceed total",
      );
      return false;
    }
    return true;
  };

  const purchaseMutation = useMutation({
    mutationFn: async () => {
      const { data: purchase, error: purchaseError } = await supabase
        .from("purchases")
        .insert({
          supplier_id: selectedSupplier.id,
          invoice_no: invoiceNo,
          purchase_date: purchaseDate,
          total_amount: totalAmount,
          discount,
          transport_cost: transportCost,
          labor_cost: laborCost,
          paid_amount: paidAmount,
          due_amount: dueAmount > 0 ? dueAmount : 0,
          payment_method: paymentMethod,
          note,
          created_by: user?.id,
        } as any)
        .select("id")
        .single();
      if (purchaseError) throw purchaseError;

      const purchaseItems = items.map((item) => {
        const baseQty = item.quantity * item.conversion_factor;
        const basePrice = item.purchase_price / item.conversion_factor;
        return {
          purchase_id: purchase.id,
          product_id: item.product_id,
          quantity: baseQty,
          purchase_price: basePrice,
          total: item.total,
        };
      });
      const { error: itemsError } = await supabase
        .from("purchase_items")
        .insert(purchaseItems);
      if (itemsError) throw itemsError;

      for (const item of items) {
        const baseQty = item.quantity * item.conversion_factor;
        const basePrice = item.purchase_price / item.conversion_factor;
        const { error: batchError } = await supabase
          .from("stock_batches")
          .insert({
            product_id: item.product_id,
            purchase_id: purchase.id,
            quantity: baseQty,
            remaining_qty: baseQty,
            purchase_price: basePrice,
          });
        if (batchError) throw batchError;

        const { data: prod } = await supabase
          .from("products")
          .select("stock_quantity")
          .eq("id", item.product_id)
          .single();
        const newStock = (Number(prod?.stock_quantity) || 0) + baseQty;
        await supabase
          .from("products")
          .update({ stock_quantity: newStock, purchase_price: basePrice })
          .eq("id", item.product_id);

        await supabase.from("stock_adjustments").insert({
          product_id: item.product_id,
          quantity_change: baseQty,
          reason: `Purchase #${invoiceNo || purchase.id} (${item.quantity} ${item.selected_unit})`,
          adjusted_by: user?.id,
        });
      }

      return purchase;
    },
    onSuccess: () => {
      toast.success(tr("purchaseSaved"));
      queryClient.invalidateQueries({ queryKey: ["purchases"] });
      queryClient.invalidateQueries({ queryKey: ["products"] });
      navigate({ to: "/purchases" });
    },
    onError: (err: any) => toast.error(err.message),
  });

  const handleSave = () => {
    setTouched(true);
    if (!validate()) return;
    purchaseMutation.mutate();
  };

  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 focus:border-primary transition-colors";

  return (
    <PageLayout>
      {/* Header */}
      <div className="mb-5 flex items-start justify-between gap-3">
        <div className="flex items-center gap-3 min-w-0">
          <div className="hidden sm:grid h-11 w-11 place-items-center rounded-xl bg-gradient-to-br from-primary to-primary/70 text-primary-foreground shadow-md shadow-primary/25 shrink-0">
            <ShoppingCart className="h-5 w-5" />
          </div>
          <div className="min-w-0">
            <h1 className="text-lg sm:text-xl font-bold text-foreground truncate">
              {tr("addPurchase")}
            </h1>
            <p className="text-xs sm:text-sm text-muted-foreground">
              {tr("addPurchaseSubtitle")}
            </p>
          </div>
        </div>
        <Link
          to="/purchases"
          className="rounded-lg border border-border bg-card px-3 py-2 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground transition-colors flex items-center gap-1 shrink-0"
        >
          <X className="h-3.5 w-3.5" />
          <span className="hidden sm:inline">{lang === "bn" ? "বাতিল" : "Cancel"}</span>
        </Link>
      </div>

      <div className="grid gap-4 lg:gap-6 lg:grid-cols-3 pb-32 lg:pb-0">
        {/* Main */}
        <div className="lg:col-span-2 space-y-4 lg:space-y-6">
          {/* Supplier */}
          <section className="rounded-xl border border-border bg-card overflow-hidden">
            <header className="flex items-center justify-between gap-2 border-b border-border bg-muted/30 px-4 py-2.5">
              <div className="flex items-center gap-2">
                <Truck className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold text-foreground">
                  {tr("supplierInfo")}
                </h3>
                {!selectedSupplier && touched && (
                  <AlertCircle className="h-3.5 w-3.5 text-red-500" />
                )}
              </div>
              {selectedSupplier && (
                <button
                  onClick={() => setSelectedSupplier(null)}
                  className="text-xs text-muted-foreground hover:text-red-500"
                >
                  {lang === "bn" ? "পরিবর্তন" : "Change"}
                </button>
              )}
            </header>

            <div className="p-4">
              {!selectedSupplier ? (
                <div ref={supplierRef} className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <input
                    className={`${inputCls} pl-9 ${!selectedSupplier && touched ? "border-red-400" : ""}`}
                    placeholder={tr("searchSupplier")}
                    value={supplierQuery}
                    onChange={(e) => setSupplierQuery(e.target.value)}
                    onFocus={() =>
                      supplierResults.length > 0 && setShowSupplierDrop(true)
                    }
                  />
                  {supplierSearching && (
                    <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />
                  )}
                  {showSupplierDrop && (
                    <div className="absolute z-30 mt-1 w-full rounded-lg border border-border bg-popover shadow-lg max-h-60 overflow-y-auto">
                      {supplierResults.length === 0 ? (
                        <div className="p-4 text-center">
                          <p className="text-xs text-muted-foreground mb-2">
                            {lang === "bn"
                              ? "কোনো সরবরাহকারী পাওয়া যায়নি"
                              : "No supplier found"}
                          </p>
                          <Link
                            to="/suppliers/add"
                            className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
                          >
                            <Plus className="h-3 w-3" />
                            {lang === "bn"
                              ? "নতুন সরবরাহকারী যোগ করুন"
                              : "Add new supplier"}
                          </Link>
                        </div>
                      ) : (
                        supplierResults.map((s: any) => (
                          <button
                            key={s.id}
                            className="w-full text-left px-4 py-2.5 text-sm hover:bg-accent border-b border-border/40 last:border-0"
                            onClick={() => {
                              setSelectedSupplier(s);
                              setShowSupplierDrop(false);
                              setSupplierQuery("");
                            }}
                          >
                            <div className="font-medium text-foreground">{s.name}</div>
                            <div className="text-xs text-muted-foreground mt-0.5 flex items-center gap-2">
                              {s.mobile && (
                                <span className="flex items-center gap-1">
                                  <Phone className="h-3 w-3" />
                                  {s.mobile}
                                </span>
                              )}
                              {Number(s.total_due) > 0 && (
                                <span className="ml-auto text-red-500 font-medium">
                                  ৳{Number(s.total_due).toLocaleString()}
                                </span>
                              )}
                            </div>
                          </button>
                        ))
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <div className="rounded-lg bg-primary/5 border border-primary/20 p-3">
                  <div className="flex items-start gap-3">
                    <div className="h-10 w-10 rounded-full bg-primary/15 grid place-items-center shrink-0">
                      <Truck className="h-4 w-4 text-primary" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="font-semibold text-foreground truncate">
                        {selectedSupplier.name}
                      </div>
                      <div className="mt-1 text-xs text-muted-foreground space-y-0.5">
                        {selectedSupplier.mobile && (
                          <div className="flex items-center gap-1.5">
                            <Phone className="h-3 w-3" />
                            {selectedSupplier.mobile}
                          </div>
                        )}
                        {selectedSupplier.address && (
                          <div className="flex items-center gap-1.5">
                            <MapPin className="h-3 w-3" />
                            <span className="truncate">{selectedSupplier.address}</span>
                          </div>
                        )}
                      </div>
                      {Number(selectedSupplier.total_due) > 0 && (
                        <div className="mt-2 inline-flex items-center gap-1 rounded-full bg-red-500/10 text-red-600 text-[11px] font-medium px-2 py-0.5">
                          {lang === "bn" ? "পূর্বের বাকি:" : "Previous due:"} ৳
                          {Number(selectedSupplier.total_due).toLocaleString()}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          </section>

          {/* Products */}
          <section className="rounded-xl border border-border bg-card overflow-hidden">
            <header className="flex items-center justify-between gap-2 border-b border-border bg-muted/30 px-4 py-2.5">
              <div className="flex items-center gap-2">
                <Package className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold text-foreground">
                  {tr("productSection")}
                </h3>
                {items.length > 0 && (
                  <span className="rounded-full bg-primary/15 text-primary text-[11px] font-semibold px-2 py-0.5">
                    {items.length}
                  </span>
                )}
              </div>
              {items.length > 0 && (
                <span className="text-xs text-muted-foreground">
                  {lang === "bn" ? "মোট পরিমাণ:" : "Total qty:"}{" "}
                  <span className="font-semibold text-foreground">{totalQty}</span>
                </span>
              )}
            </header>

            <div className="p-4">
              <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
                  ref={prodInputRef}
                  className={`${inputCls} pl-9`}
                  placeholder={tr("searchProduct")}
                  value={prodQuery}
                  onChange={(e) => setProdQuery(e.target.value)}
                  onFocus={() => prodResults.length > 0 && setShowProdDrop(true)}
                />
                {prodSearching && (
                  <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />
                )}
                {showProdDrop && prodResults.length > 0 && (
                  <div className="absolute z-30 mt-1 w-full rounded-lg border border-border bg-popover shadow-lg max-h-60 overflow-y-auto">
                    {prodResults.map((p: any) => (
                      <button
                        key={p.id}
                        className="w-full text-left px-4 py-2.5 text-sm hover:bg-accent border-b border-border/40 last:border-0"
                        onClick={() => addProduct(p)}
                      >
                        <div className="flex items-center justify-between gap-2">
                          <div className="font-medium text-foreground truncate">
                            {p.name}
                          </div>
                          <span className="text-xs font-semibold text-primary shrink-0">
                            ৳{Number(p.purchase_price || 0).toLocaleString()}
                          </span>
                        </div>
                        <div className="text-xs text-muted-foreground mt-0.5 flex items-center gap-2">
                          {p.sku && (
                            <span className="flex items-center gap-1">
                              <Hash className="h-2.5 w-2.5" />
                              {p.sku}
                            </span>
                          )}
                          <span
                            className={`ml-auto font-medium ${Number(p.stock_quantity) <= 0 ? "text-red-500" : "text-emerald-600"}`}
                          >
                            {tr("stock")}: {p.stock_quantity}
                          </span>
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {items.length === 0 ? (
                <div className="rounded-lg border-2 border-dashed border-border py-10 text-center">
                  <Package className="h-8 w-8 mx-auto text-muted-foreground/40 mb-2" />
                  <p className="text-sm text-muted-foreground">
                    {lang === "bn"
                      ? "উপরের সার্চ বার থেকে পণ্য যোগ করুন"
                      : "Search above to add products"}
                  </p>
                  {touched && (
                    <p className="text-xs text-red-500 mt-2">
                      {lang === "bn"
                        ? "অন্তত একটি পণ্য প্রয়োজন"
                        : "At least one product required"}
                    </p>
                  )}
                </div>
              ) : (
                <>
                  {/* Mobile: card list */}
                  <div className="md:hidden space-y-3">
                    {items.map((item, idx) => (
                      <div
                        key={item.product_id}
                        className="rounded-lg border border-border bg-background p-3 space-y-2"
                      >
                        <div className="flex items-start justify-between gap-2">
                          <div className="min-w-0 flex-1">
                            <div className="font-medium text-sm text-foreground">
                              {item.product_name}
                            </div>
                            <div className="text-[11px] text-muted-foreground">
                              {tr("stock")}: {item.current_stock} {item.base_unit}
                            </div>
                          </div>
                          <button
                            onClick={() => removeItem(idx)}
                            className="h-7 w-7 grid place-items-center rounded-md text-red-500 hover:bg-red-500/10"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </button>
                        </div>

                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <label className="text-[10px] text-muted-foreground uppercase tracking-wide">
                              {tr("selectUnit")}
                            </label>
                            <select
                              className="w-full rounded-md border border-border bg-card px-2 py-1.5 text-sm mt-0.5"
                              value={item.selected_unit}
                              onChange={(e) => updateItemUnit(idx, e.target.value)}
                            >
                              {item.available_units.map((u) => (
                                <option key={u.unit_name} value={u.unit_name}>
                                  {u.unit_name}
                                  {u.conversion_factor > 1
                                    ? ` (×${u.conversion_factor})`
                                    : ""}
                                </option>
                              ))}
                            </select>
                          </div>
                          <div>
                            <label className="text-[10px] text-muted-foreground uppercase tracking-wide">
                              {tr("purchasePrice")}
                            </label>
                            <input
                              type="number"
                              min={0}
                              className="w-full rounded-md border border-border bg-card px-2 py-1.5 text-sm mt-0.5"
                              value={item.purchase_price}
                              onFocus={(e) => e.target.select()}
                              onChange={(e) =>
                                updateItem(idx, "purchase_price", Number(e.target.value) || 0)
                              }
                            />
                          </div>
                        </div>

                        <div className="flex items-center justify-between gap-2">
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => stepQty(idx, -1)}
                              className="h-8 w-8 grid place-items-center rounded-md border border-border hover:bg-accent"
                              aria-label="Decrease"
                            >
                              <Minus className="h-3.5 w-3.5" />
                            </button>
                            <input
                              type="number"
                              min={1}
                              className="w-16 text-center rounded-md border border-border bg-card px-1 py-1.5 text-sm font-medium"
                              value={item.quantity}
                              onFocus={(e) => e.target.select()}
                              onChange={(e) =>
                                updateItem(idx, "quantity", Number(e.target.value) || 1)
                              }
                            />
                            <button
                              onClick={() => stepQty(idx, 1)}
                              className="h-8 w-8 grid place-items-center rounded-md border border-border hover:bg-accent"
                              aria-label="Increase"
                            >
                              <Plus className="h-3.5 w-3.5" />
                            </button>
                          </div>
                          <div className="text-right">
                            <div className="text-[10px] text-muted-foreground uppercase">
                              {tr("total")}
                            </div>
                            <div className="font-bold text-primary">
                              ৳{item.total.toLocaleString()}
                            </div>
                          </div>
                        </div>

                        {item.conversion_factor > 1 && (
                          <div className="text-[10px] text-muted-foreground text-center bg-muted/40 rounded py-1">
                            = {item.quantity * item.conversion_factor} {item.base_unit}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>

                  {/* Desktop: table */}
                  <div className="hidden md:block overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-border text-left text-xs text-muted-foreground uppercase tracking-wide">
                          <th className="pb-2 font-medium">{tr("productName")}</th>
                          <th className="pb-2 font-medium w-28">{tr("selectUnit")}</th>
                          <th className="pb-2 font-medium w-28">{tr("quantity")}</th>
                          <th className="pb-2 font-medium w-32">{tr("purchasePrice")}</th>
                          <th className="pb-2 font-medium w-28 text-right">{tr("total")}</th>
                          <th className="pb-2 w-10"></th>
                        </tr>
                      </thead>
                      <tbody>
                        {items.map((item, idx) => (
                          <tr
                            key={item.product_id}
                            className="border-b border-border/30 hover:bg-muted/20"
                          >
                            <td className="py-2.5">
                              <div className="font-medium text-foreground">
                                {item.product_name}
                              </div>
                              <div className="text-[11px] text-muted-foreground">
                                {tr("stock")}: {item.current_stock} {item.base_unit}
                                {item.conversion_factor > 1 && (
                                  <>
                                    {" "}
                                    · = {item.quantity * item.conversion_factor}{" "}
                                    {item.base_unit}
                                  </>
                                )}
                              </div>
                            </td>
                            <td className="py-2.5">
                              <select
                                className="w-full rounded border border-border bg-background px-2 py-1 text-sm"
                                value={item.selected_unit}
                                onChange={(e) => updateItemUnit(idx, e.target.value)}
                              >
                                {item.available_units.map((u) => (
                                  <option key={u.unit_name} value={u.unit_name}>
                                    {u.unit_name}
                                    {u.conversion_factor > 1
                                      ? ` (×${u.conversion_factor})`
                                      : ""}
                                  </option>
                                ))}
                              </select>
                            </td>
                            <td className="py-2.5">
                              <div className="flex items-center gap-1">
                                <button
                                  onClick={() => stepQty(idx, -1)}
                                  className="h-7 w-7 grid place-items-center rounded border border-border hover:bg-accent"
                                >
                                  <Minus className="h-3 w-3" />
                                </button>
                                <input
                                  type="number"
                                  min={1}
                                  className="w-14 text-center rounded border border-border bg-background px-1 py-1 text-sm"
                                  value={item.quantity}
                                  onFocus={(e) => e.target.select()}
                                  onChange={(e) =>
                                    updateItem(idx, "quantity", Number(e.target.value) || 1)
                                  }
                                />
                                <button
                                  onClick={() => stepQty(idx, 1)}
                                  className="h-7 w-7 grid place-items-center rounded border border-border hover:bg-accent"
                                >
                                  <Plus className="h-3 w-3" />
                                </button>
                              </div>
                            </td>
                            <td className="py-2.5">
                              <input
                                type="number"
                                min={0}
                                className="w-28 rounded border border-border bg-background px-2 py-1 text-sm"
                                value={item.purchase_price}
                                onFocus={(e) => e.target.select()}
                                onChange={(e) =>
                                  updateItem(
                                    idx,
                                    "purchase_price",
                                    Number(e.target.value) || 0,
                                  )
                                }
                              />
                            </td>
                            <td className="py-2.5 text-right font-semibold text-primary">
                              ৳{item.total.toLocaleString()}
                            </td>
                            <td className="py-2.5">
                              <button
                                onClick={() => removeItem(idx)}
                                className="h-7 w-7 grid place-items-center rounded text-red-500 hover:bg-red-500/10"
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </>
              )}
            </div>
          </section>
        </div>

        {/* Right Panel */}
        <div className="space-y-4">
          {/* Invoice meta */}
          <section className="rounded-xl border border-border bg-card overflow-hidden">
            <header className="flex items-center gap-2 border-b border-border bg-muted/30 px-4 py-2.5">
              <FileText className="h-4 w-4 text-primary" />
              <h3 className="text-sm font-semibold text-foreground">
                {lang === "bn" ? "ক্রয়ের বিবরণ" : "Purchase Details"}
              </h3>
            </header>
            <div className="p-4 space-y-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground flex items-center gap-1 mb-1">
                  <Hash className="h-3 w-3" />
                  {tr("invoiceNo")}
                </label>
                <input
                  className={inputCls}
                  placeholder={lang === "bn" ? "ঐচ্ছিক" : "Optional"}
                  value={invoiceNo}
                  onChange={(e) => setInvoiceNo(e.target.value)}
                />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground flex items-center gap-1 mb-1">
                  <Calendar className="h-3 w-3" />
                  {tr("purchaseDate")}
                </label>
                <input
                  type="date"
                  className={inputCls}
                  value={purchaseDate}
                  onChange={(e) => setPurchaseDate(e.target.value)}
                />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground mb-1 block">
                  {tr("note")}
                </label>
                <textarea
                  className={inputCls}
                  rows={2}
                  placeholder={lang === "bn" ? "ঐচ্ছিক" : "Optional"}
                  value={note}
                  onChange={(e) => setNote(e.target.value)}
                />
              </div>
            </div>
          </section>

          {/* Payment */}
          <section className="rounded-xl border border-border bg-card overflow-hidden">
            <header className="flex items-center gap-2 border-b border-border bg-muted/30 px-4 py-2.5">
              <Wallet className="h-4 w-4 text-primary" />
              <h3 className="text-sm font-semibold text-foreground">
                {tr("paymentSummary")}
              </h3>
            </header>
            <div className="p-4 space-y-3">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">{tr("subtotal")}</span>
                <span className="font-medium">৳{subtotal.toLocaleString()}</span>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground mb-1 block">
                  {tr("discount")}
                </label>
                <input
                  type="number"
                  min={0}
                  className={inputCls}
                  value={discount}
                  onFocus={(e) => e.target.select()}
                  onChange={(e) => setDiscount(Number(e.target.value) || 0)}
                />
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1">
                    <Truck className="h-3 w-3" />
                    {lang === "bn" ? "পরিবহন খরচ" : "Transport"}
                  </label>
                  <input
                    type="number"
                    min={0}
                    className={inputCls}
                    value={transportCost}
                    onFocus={(e) => e.target.select()}
                    onChange={(e) => setTransportCost(Number(e.target.value) || 0)}
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1">
                    <Package className="h-3 w-3" />
                    {lang === "bn" ? "লেবার খরচ" : "Labor"}
                  </label>
                  <input
                    type="number"
                    min={0}
                    className={inputCls}
                    value={laborCost}
                    onFocus={(e) => e.target.select()}
                    onChange={(e) => setLaborCost(Number(e.target.value) || 0)}
                  />
                </div>
              </div>
              <div className="flex justify-between text-base font-bold border-t border-border pt-3">
                <span>{tr("total")}</span>
                <span className="text-primary">৳{totalAmount.toLocaleString()}</span>
              </div>


              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="text-xs font-medium text-muted-foreground">
                    {tr("paidAmount")}
                  </label>
                  <div className="flex gap-1">
                    <button
                      type="button"
                      onClick={setPayNone}
                      className="text-[10px] font-medium px-2 py-0.5 rounded bg-muted hover:bg-accent text-muted-foreground"
                    >
                      0%
                    </button>
                    <button
                      type="button"
                      onClick={setPayHalf}
                      className="text-[10px] font-medium px-2 py-0.5 rounded bg-muted hover:bg-accent text-muted-foreground"
                    >
                      50%
                    </button>
                    <button
                      type="button"
                      onClick={setPayFull}
                      className="text-[10px] font-medium px-2 py-0.5 rounded bg-primary/15 hover:bg-primary/25 text-primary"
                    >
                      100%
                    </button>
                  </div>
                </div>
                <input
                  type="number"
                  min={0}
                  className={inputCls}
                  value={paidAmount}
                  onFocus={(e) => e.target.select()}
                  onChange={(e) => setPaidAmount(Number(e.target.value) || 0)}
                />
              </div>

              <div className="flex justify-between items-center text-sm rounded-lg bg-muted/40 px-3 py-2">
                <span className="text-muted-foreground">{tr("dueAmount")}</span>
                <span
                  className={`font-bold text-base ${dueAmount > 0 ? "text-red-500" : "text-emerald-600"}`}
                >
                  ৳{Math.max(0, dueAmount).toLocaleString()}
                </span>
              </div>

              <div>
                <label className="text-xs font-medium text-muted-foreground mb-1 block">
                  {tr("paymentMethod")}
                </label>
                <select
                  className={inputCls}
                  value={paymentMethod}
                  onChange={(e) => setPaymentMethod(e.target.value)}
                >
                  <option value="cash">{tr("cash")}</option>
                  <option value="bkash">{tr("bkash")}</option>
                  <option value="bank">{tr("bankTransfer")}</option>
                  <option value="card">{tr("card")}</option>
                </select>
              </div>

              {/* Desktop save button */}
              <button
                onClick={handleSave}
                disabled={purchaseMutation.isPending}
                className="hidden lg:flex w-full rounded-lg bg-gradient-to-r from-primary to-primary/85 hover:from-primary/95 hover:to-primary py-3 text-sm font-semibold text-primary-foreground shadow-md shadow-primary/25 disabled:opacity-60 items-center justify-center gap-2 transition-all"
              >
                {purchaseMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Save className="h-4 w-4" />
                )}
                {tr("savePurchase")}
              </button>
            </div>
          </section>
        </div>
      </div>

      {/* Mobile sticky bottom bar */}
      <div className="lg:hidden fixed bottom-0 left-0 right-0 z-40 bg-card/95 backdrop-blur border-t border-border px-4 py-3 shadow-[0_-4px_12px_rgba(0,0,0,0.06)]">
        <div className="flex items-center justify-between gap-3">
          <div className="min-w-0">
            <div className="text-[10px] text-muted-foreground uppercase tracking-wide">
              {tr("total")}
            </div>
            <div className="text-lg font-bold text-primary leading-tight">
              ৳{totalAmount.toLocaleString()}
            </div>
            {dueAmount > 0 && (
              <div className="text-[10px] text-red-500">
                {tr("dueAmount")}: ৳{dueAmount.toLocaleString()}
              </div>
            )}
          </div>
          <button
            onClick={handleSave}
            disabled={purchaseMutation.isPending}
            className="flex-1 max-w-[200px] rounded-lg bg-gradient-to-r from-primary to-primary/85 py-3 text-sm font-semibold text-primary-foreground shadow-md shadow-primary/25 disabled:opacity-60 flex items-center justify-center gap-2"
          >
            {purchaseMutation.isPending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <CheckCircle2 className="h-4 w-4" />
            )}
            {tr("savePurchase")}
          </button>
        </div>
      </div>
    </PageLayout>
  );
}

// Internal use only — kept to satisfy unused-import lints if Receipt becomes used.
void Receipt;
