import { createFileRoute, useNavigate } 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 } from "react";
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { Search, Trash2, Loader2, Printer } from "lucide-react";
import { useReceiptPrint } from "@/components/ReceiptPrint";

export const Route = createFileRoute("/_authenticated/sales-orders/create")({
  head: () => ({
    meta: [
      { title: "নতুন Sales Order — Niyamah ERP" },
      { name: "description", content: "Create new sales order / quotation" },
    ],
  }),
  component: CreateSalesOrderPage,
});

type OrderItem = {
  product_id: string;
  product_name: string;
  quantity: number;
  price: number;
  total: number;
  stock: number;
};

function CreateSalesOrderPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const { user } = useAuth();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { printReceipt } = useReceiptPrint();

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

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

  const [items, setItems] = useState<OrderItem[]>([]);
  const [discount, setDiscount] = useState(0);
  const [paidAmount, setPaidAmount] = useState(0);
  const [paymentMethod, setPaymentMethod] = useState("cash");
  const [orderDate, setOrderDate] = useState(new Date().toISOString().split("T")[0]);
  const [deliveryDate, setDeliveryDate] = useState("");
  const [branchId, setBranchId] = useState<string>("");
  const [status, setStatus] = useState("pending");
  const [note, setNote] = useState("");

  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 subtotal = items.reduce((s, i) => s + i.total, 0);
  const totalAmount = Math.max(0, subtotal - discount);
  const dueAmount = Math.max(0, totalAmount - paidAmount);

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

  useEffect(() => {
    if (prodQuery.length < 2) { setProdResults([]); return; }
    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 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 addProduct = (p: any) => {
    const exist = items.find((i) => i.product_id === p.id);
    const price = Number(p.retail_price) || 0;
    if (exist) {
      setItems(items.map((i) => i.product_id === p.id
        ? { ...i, quantity: i.quantity + 1, total: (i.quantity + 1) * i.price }
        : i));
    } else {
      setItems([...items, {
        product_id: p.id,
        product_name: p.name,
        quantity: 1,
        price,
        total: price,
        stock: Number(p.stock_quantity) || 0,
      }]);
    }
    setProdQuery("");
    setShowProdDrop(false);
  };

  const updateItem = (idx: number, field: "quantity" | "price", value: number) => {
    setItems(items.map((it, i) => {
      if (i !== idx) return it;
      const u = { ...it, [field]: value };
      u.total = u.quantity * u.price;
      return u;
    }));
  };

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

  const saveMutation = useMutation({
    mutationFn: async (withPrint: boolean) => {
      if (items.length === 0) throw new Error(isBn ? "অন্তত একটি পণ্য যোগ করুন" : "Add at least one product");
      // Stock validation
      const oversold = items.find((it) => it.quantity > it.stock);
      if (oversold) {
        throw new Error(
          isBn
            ? `${oversold.product_name}: পর্যাপ্ত স্টক নেই (স্টক: ${oversold.stock})`
            : `${oversold.product_name}: insufficient stock (have ${oversold.stock})`
        );
      }

      const { data: order, error: orderErr } = await supabase
        .from("sales_orders" as any)
        .insert({
          customer_id: selectedCust?.id || null,
          branch_id: branchId || null,
          order_date: orderDate,
          delivery_date: deliveryDate || null,
          total_amount: totalAmount,
          discount,
          paid_amount: paidAmount,
          due_amount: dueAmount,
          payment_method: paymentMethod,
          status,
          note,
          created_by: user?.id,
        } as any)
        .select("id, order_no")
        .single();
      if (orderErr) throw orderErr;

      const rows = items.map((it) => ({
        sales_order_id: (order as any).id,
        product_id: it.product_id,
        quantity: it.quantity,
        price: it.price,
        total: it.total,
      }));
      const { error: itemsErr } = await supabase.from("sales_order_items" as any).insert(rows);
      if (itemsErr) throw itemsErr;

      // Deduct stock for each product
      await Promise.all(
        items.map((it) =>
          supabase
            .from("products")
            .update({ stock_quantity: Math.max(0, (it.stock || 0) - it.quantity) } as any)
            .eq("id", it.product_id)
        )
      );

      // Update customer due if applicable
      if (selectedCust?.id && dueAmount > 0) {
        const newDue = Number(selectedCust.total_due || 0) + dueAmount;
        await supabase
          .from("customers")
          .update({ total_due: newDue } as any)
          .eq("id", selectedCust.id);
      }

      // Record payment as wallet/cash transaction reference (optional ledger)
      if (paidAmount > 0 && selectedCust?.id) {
        await supabase.from("wallet_transactions" as any).insert({
          customer_id: selectedCust.id,
          type: "payment",
          amount: paidAmount,
          balance_after: 0,
          reference_id: (order as any).order_no,
          note: `Sales Order payment (${paymentMethod})`,
        } as any);
      }

      return { order, withPrint };
    },
    onSuccess: async ({ order, withPrint }: any) => {
      toast.success(isBn ? `অর্ডার তৈরি হয়েছে: ${order.order_no}` : `Order created: ${order.order_no}`);
      qc.invalidateQueries({ queryKey: ["sales-orders"] });
      if (withPrint) {
        await printReceipt({
          invoiceNo: order.order_no || "",
          date: orderDate,
          customer: selectedCust?.name || "",
          phone: selectedCust?.mobile || "",
          address: selectedCust?.address || "",
          saleMan: user?.email || "",
          items: items.map((it) => ({
            name: it.product_name,
            code: "",
            quantity: it.quantity,
            unitPrice: it.price,
            discount: 0,
          })),
          subTotal: subtotal,
          discount,
          expense: 0,
          grandTotal: totalAmount,
          paid: paidAmount,
          due: dueAmount,
          billStatus: "final",
        });
      }
      navigate({ to: "/sales-orders" });
    },
    onError: (e: any) => toast.error(e.message),
  });

  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";

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{isBn ? "নতুন Sales Order" : "New Sales Order"}</h1>
        <p className="text-sm text-muted-foreground">{isBn ? "গ্রাহকের অর্ডার / কোটেশন তৈরি করুন" : "Create a customer order / quotation"}</p>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2 space-y-6">
          <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">
              <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={selectedCust ? selectedCust.name : custQuery}
                onChange={(e) => { setCustQuery(e.target.value); setSelectedCust(null); }}
                onFocus={() => custResults.length > 0 && setShowCustDrop(true)}
              />
              {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={() => { setSelectedCust(c); setShowCustDrop(false); setCustQuery(""); }}
                    >
                      <div className="font-medium">{c.name}</div>
                      <div className="text-xs text-muted-foreground">{c.mobile}</div>
                    </button>
                  ))}
                </div>
              )}
            </div>
            {selectedCust && (
              <div className="mt-2 text-xs text-muted-foreground">
                📞 {selectedCust.mobile} · {isBn ? "বকেয়া" : "Due"}: ৳{Number(selectedCust.total_due || 0).toLocaleString()}
              </div>
            )}
          </div>

          <div className="rounded-xl border border-border bg-card p-5">
            <h3 className="text-sm font-semibold mb-3">{isBn ? "পণ্য যোগ করুন" : "Add Products"}</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 ? "পণ্য খুঁজুন" : "Search product"}
                value={prodQuery}
                onChange={(e) => setProdQuery(e.target.value)}
                onFocus={() => prodResults.length > 0 && setShowProdDrop(true)}
              />
              {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-24">{isBn ? "পরিমাণ" : "Qty"}</th>
                      <th className="pb-2 font-medium w-32">{isBn ? "মূল্য" : "Price"}</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} className="border-b border-border/30">
                        <td className="py-2">
                          <div>{it.product_name}</div>
                          <div className="text-[11px] text-muted-foreground">{isBn ? "স্টক" : "Stock"}: {it.stock}</div>
                        </td>
                        <td className="py-2">
                          <input type="number" min={1}
                            className="w-20 rounded border border-border bg-background px-2 py-1 text-sm"
                            value={it.quantity}
                            onChange={(e) => updateItem(idx, "quantity", Number(e.target.value) || 1)}
                          />
                        </td>
                        <td className="py-2">
                          <input type="number" min={0}
                            className="w-28 rounded border border-border bg-background px-2 py-1 text-sm"
                            value={it.price}
                            onChange={(e) => updateItem(idx, "price", Number(e.target.value) || 0)}
                          />
                        </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>
        </div>

        <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 ? "অর্ডার তারিখ" : "Order Date"}</label>
              <input type="date" className={inputCls} value={orderDate} onChange={(e) => setOrderDate(e.target.value)} />
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "ডেলিভারি তারিখ" : "Delivery Date"}</label>
              <input type="date" className={inputCls} value={deliveryDate} onChange={(e) => setDeliveryDate(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="">{isBn ? "—" : "—"}</option>
                {branches.map((b: any) => <option key={b.id} value={b.id}>{b.name}</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "স্ট্যাটাস" : "Status"}</label>
              <select className={inputCls} value={status} onChange={(e) => setStatus(e.target.value)}>
                <option value="pending">{isBn ? "অপেক্ষমাণ" : "Pending"}</option>
                <option value="confirmed">{isBn ? "নিশ্চিত" : "Confirmed"}</option>
                <option value="delivered">{isBn ? "ডেলিভার্ড" : "Delivered"}</option>
              </select>
            </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>
              <label className="text-xs font-medium text-muted-foreground">{isBn ? "ছাড়" : "Discount"}</label>
              <input type="number" min={0} className={inputCls} value={discount} onChange={(e) => setDiscount(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 ? "অগ্রিম পেমেন্ট" : "Advance 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 className="grid grid-cols-2 gap-2">
              <button
                onClick={() => saveMutation.mutate(false)}
                disabled={saveMutation.isPending || items.length === 0}
                className="rounded-lg border border-border bg-background py-2.5 text-sm font-semibold text-foreground hover:bg-accent disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {saveMutation.isPending && saveMutation.variables === false ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                {isBn ? "শুধু সংরক্ষণ" : "Save"}
              </button>
              <button
                onClick={() => saveMutation.mutate(true)}
                disabled={saveMutation.isPending || items.length === 0}
                className="rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {saveMutation.isPending && saveMutation.variables === true ? <Loader2 className="h-4 w-4 animate-spin" /> : <Printer className="h-4 w-4" />}
                {isBn ? "সংরক্ষণ ও প্রিন্ট" : "Save & Print"}
              </button>
            </div>
          </div>
        </div>
      </div>
    </PageLayout>
  );
}
