import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useReceiptPrint } from "@/components/ReceiptPrint";
import { Plus, Trash2, Eye, Printer, Search, Pencil } from "lucide-react";
import { useMemo, useState } from "react";
import { SALE_STATUSES, STATUS_COLORS, statusLabel, type SaleStatus } from "@/components/sales/sale-status";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

export const Route = createFileRoute("/_authenticated/sales/")({
  head: () => ({
    meta: [
      { title: "Sale Invoice তালিকা — Niyamah ERP" },
      { name: "description", content: "সকল sale invoice এর তালিকা" },
    ],
  }),
  component: SalesListPage,
});

function SalesListPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const qc = useQueryClient();
  const { printReceipt } = useReceiptPrint();
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [viewId, setViewId] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<SaleStatus | "all">("all");

  const { data: sales = [], isLoading } = useQuery({
    queryKey: ["sales-list"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("sales" as any)
        .select("*")
        .order("created_at", { ascending: false })
        .limit(500);
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const { data: viewData } = useQuery({
    queryKey: ["sales-detail", viewId],
    enabled: !!viewId,
    queryFn: async () => {
      const [{ data: sale }, { data: items }] = await Promise.all([
        supabase.from("sales" as any).select("*").eq("id", viewId!).single(),
        supabase.from("sale_items" as any).select("*").eq("sale_id", viewId!),
      ]);
      return { sale: sale as any, items: (items as any[]) || [] };
    },
  });

  const deleteMut = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("sales" as any).delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "ইনভয়েস ডিলিট হয়েছে" : "Invoice deleted");
      qc.invalidateQueries({ queryKey: ["sales-list"] });
      setDeleteId(null);
    },
    onError: (e: any) => toast.error(e.message),
  });

  const statusCounts = useMemo(() => {
    const map = new Map<string, number>();
    for (const s of sales as any[]) {
      const k = s.sale_status || s.status || "completed";
      map.set(k, (map.get(k) || 0) + 1);
    }
    return map;
  }, [sales]);

  const maxCount = useMemo(() => {
    let m = 0;
    for (const v of statusCounts.values()) if (v > m) m = v;
    return m || 1;
  }, [statusCounts]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return (sales as any[]).filter((s: any) => {
      const sStatus = s.sale_status || s.status || "completed";
      if (statusFilter !== "all" && sStatus !== statusFilter) return false;
      if (!q) return true;
      return (
        String(s.invoice_no || "").toLowerCase().includes(q) ||
        String(s.customer_name || "").toLowerCase().includes(q) ||
        String(s.customer_mobile || "").toLowerCase().includes(q)
      );
    });
  }, [sales, search, statusFilter]);

  const printOne = async (id: string) => {
    const [{ data: sale }, { data: items }] = await Promise.all([
      supabase.from("sales" as any).select("*").eq("id", id).single(),
      supabase.from("sale_items" as any).select("*").eq("sale_id", id),
    ]);
    if (!sale) return;
    const s = sale as any;
    await printReceipt({
      invoiceNo: s.invoice_no,
      date: new Date(s.sale_date).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-GB"),
      customer: s.customer_name || "",
      phone: s.customer_mobile || "",
      address: s.customer_address || "",
      saleMan: s.sale_man || "",
      items: ((items as any[]) || []).map((it) => ({
        name: lang === "bn" ? it.name_bn || it.name : it.name,
        code: it.barcode || "",
        quantity: Number(it.quantity),
        unit: it.unit,
        unitPrice: Number(it.unit_price),
        discount: Number(it.unit_discount) * Number(it.quantity),
      })),
      subTotal: Number(s.subtotal),
      discount: Number(s.discount),
      expense: Number(s.expense),
      grandTotal: Number(s.total_amount),
      paid: Number(s.paid_amount),
      due: Number(s.due_amount),
    });
  };

  return (
    <PageLayout>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">{isBn ? "Sale Invoice তালিকা" : "Sale Invoices"}</h1>
          <p className="text-sm text-muted-foreground">
            {isBn ? "সকল বিক্রয় ইনভয়েস" : "All sale invoices"}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <div className="relative">
            <Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={isBn ? "ইনভয়েস/কাস্টমার/মোবাইল" : "Invoice / Customer / Mobile"}
              className="w-64 rounded-lg border border-border bg-card pl-8 pr-3 py-2 text-sm"
            />
          </div>
          <Link
            to="/sales/create"
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:opacity-90"
          >
            <Plus className="h-4 w-4" />
            {isBn ? "নতুন বিক্রয়" : "New Sale"}
          </Link>
        </div>
      </div>

      {/* Status counts chart + filter chips */}
      <div className="mb-4 rounded-xl border border-border bg-card p-4">
        <div className="mb-3 flex items-center justify-between">
          <div className="text-sm font-semibold text-foreground">
            {isBn ? "স্ট্যাটাস অনুযায়ী বিক্রয়" : "Sales by Status"}
          </div>
          <div className="text-xs text-muted-foreground">
            {isBn ? "মোট" : "Total"}: {sales.length}
          </div>
        </div>
        <div className="flex flex-wrap gap-2 mb-4">
          <button
            onClick={() => setStatusFilter("all")}
            className={`rounded-full border px-3 py-1 text-xs font-medium ${
              statusFilter === "all"
                ? "bg-primary text-primary-foreground border-primary"
                : "bg-card text-foreground border-border hover:bg-muted"
            }`}
          >
            {isBn ? "সব" : "All"} ({sales.length})
          </button>
          {SALE_STATUSES.map((s) => {
            const count = statusCounts.get(s) || 0;
            const active = statusFilter === s;
            return (
              <button
                key={s}
                onClick={() => setStatusFilter(active ? "all" : s)}
                className={`rounded-full border px-3 py-1 text-xs font-medium ${active ? "ring-2 ring-primary " : ""}${STATUS_COLORS[s]}`}
              >
                {statusLabel(s, isBn)} ({count})
              </button>
            );
          })}
        </div>
        <div className="grid grid-cols-3 sm:grid-cols-5 lg:grid-cols-9 gap-3">
          {SALE_STATUSES.map((s) => {
            const count = statusCounts.get(s) || 0;
            const pct = (count / maxCount) * 100;
            return (
              <button
                key={s}
                onClick={() => setStatusFilter(statusFilter === s ? "all" : s)}
                className="flex flex-col items-center gap-1 group"
                title={`${statusLabel(s, isBn)}: ${count}`}
              >
                <div className="h-20 w-full flex items-end">
                  <div
                    className={`w-full rounded-t-md border ${STATUS_COLORS[s]} transition-all group-hover:opacity-80`}
                    style={{ height: `${Math.max(pct, 4)}%` }}
                  />
                </div>
                <div className="text-[10px] text-muted-foreground text-center leading-tight">
                  {statusLabel(s, isBn)}
                </div>
                <div className="text-xs font-semibold text-foreground">{count}</div>
              </button>
            );
          })}
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border text-left text-xs text-muted-foreground">
              <th className="px-4 py-3 font-medium">{isBn ? "ইনভয়েস" : "Invoice"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "তারিখ" : "Date"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "কাস্টমার" : "Customer"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "মোট" : "Total"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "পেইড" : "Paid"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "বকেয়া" : "Due"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "সেল স্ট্যাটাস" : "Sale Status"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "ডেলিভারি" : "Delivery"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "পেমেন্ট" : "Method"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "অ্যাকশন" : "Actions"}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr><td colSpan={10} className="px-4 py-8 text-center text-muted-foreground">{isBn ? "লোড হচ্ছে..." : "Loading..."}</td></tr>
            ) : filtered.length === 0 ? (
              <tr><td colSpan={10} className="px-4 py-8 text-center text-muted-foreground">{isBn ? "কোনো ইনভয়েস নেই" : "No invoices"}</td></tr>
            ) : (
              filtered.map((s: any) => (
                <tr key={s.id} className="border-b border-border last:border-0">
                  <td className="px-4 py-3 font-mono text-xs">{s.invoice_no}</td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">
                    {new Date(s.sale_date).toLocaleDateString(isBn ? "bn-BD" : "en-GB")}
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-foreground">{s.customer_name || (isBn ? "ওয়াক-ইন" : "Walk-in")}</div>
                    {s.customer_mobile && <div className="text-xs text-muted-foreground">{s.customer_mobile}</div>}
                  </td>
                  <td className="px-4 py-3 text-right font-semibold">৳{Number(s.total_amount).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-green-600">৳{Number(s.paid_amount).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-orange-600">৳{Number(s.due_amount).toLocaleString()}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-semibold ${STATUS_COLORS[(s.sale_status || s.status || "completed") as SaleStatus] || "bg-muted text-muted-foreground border-border"}`}>
                      {statusLabel(s.sale_status || s.status || "completed", isBn)}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center rounded-full border border-border bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground">
                      {(() => {
                        const d = s.delivery_status || "pending";
                        const map: Record<string, { en: string; bn: string }> = {
                          pending: { en: "Pending", bn: "অপেক্ষমাণ" },
                          partial: { en: "Partial", bn: "আংশিক" },
                          delivered: { en: "Delivered", bn: "ডেলিভার্ড" },
                        };
                        return map[d] ? map[d][isBn ? "bn" : "en"] : d;
                      })()}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="rounded-full bg-secondary px-2 py-0.5 text-xs text-secondary-foreground">
                      {s.payment_method}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-1">
                      <button
                        onClick={() => setViewId(s.id)}
                        className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground"
                        title={isBn ? "দেখুন" : "View"}
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <Link
                        to="/sales/$saleId/edit"
                        params={{ saleId: s.id }}
                        className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground"
                        title={isBn ? "এডিট" : "Edit"}
                      >
                        <Pencil className="h-4 w-4" />
                      </Link>
                      <button
                        onClick={() => printOne(s.id)}
                        className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground"
                        title={isBn ? "প্রিন্ট" : "Print"}
                      >
                        <Printer className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => setDeleteId(s.id)}
                        className="rounded-md p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
                        title={isBn ? "ডিলিট" : "Delete"}
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <Dialog open={!!viewId} onOpenChange={(o) => !o && setViewId(null)}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {isBn ? "ইনভয়েস" : "Invoice"} #{viewData?.sale?.invoice_no}
            </DialogTitle>
          </DialogHeader>
          {viewData?.sale && (
            <div className="space-y-4 text-sm">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <div className="text-xs text-muted-foreground">{isBn ? "কাস্টমার" : "Customer"}</div>
                  <div className="font-medium">{viewData.sale.customer_name || "—"}</div>
                  {viewData.sale.customer_mobile && (
                    <div className="text-xs text-muted-foreground">{viewData.sale.customer_mobile}</div>
                  )}
                </div>
                <div className="text-right">
                  <div className="text-xs text-muted-foreground">{isBn ? "তারিখ" : "Date"}</div>
                  <div className="font-medium">
                    {new Date(viewData.sale.sale_date).toLocaleDateString(isBn ? "bn-BD" : "en-GB")}
                  </div>
                  {viewData.sale.sale_man && (
                    <div className="text-xs text-muted-foreground">{isBn ? "সেলসম্যান" : "Sales"}: {viewData.sale.sale_man}</div>
                  )}
                </div>
              </div>

              <div className="rounded-lg border border-border overflow-hidden">
                <table className="w-full text-xs">
                  <thead className="bg-muted/50">
                    <tr>
                      <th className="px-2 py-2 text-left">{isBn ? "পণ্য" : "Item"}</th>
                      <th className="px-2 py-2 text-right">{isBn ? "পরিমাণ" : "Qty"}</th>
                      <th className="px-2 py-2 text-right">{isBn ? "দাম" : "Price"}</th>
                      <th className="px-2 py-2 text-right">{isBn ? "ডিসকাউন্ট" : "Disc"}</th>
                      <th className="px-2 py-2 text-right">{isBn ? "মোট" : "Total"}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {viewData.items.map((it: any) => (
                      <tr key={it.id} className="border-t border-border">
                        <td className="px-2 py-2">{lang === "bn" ? it.name_bn || it.name : it.name}</td>
                        <td className="px-2 py-2 text-right">{Number(it.quantity)} {it.unit}</td>
                        <td className="px-2 py-2 text-right">৳{Number(it.unit_price).toLocaleString()}</td>
                        <td className="px-2 py-2 text-right">৳{(Number(it.unit_discount) * Number(it.quantity)).toLocaleString()}</td>
                        <td className="px-2 py-2 text-right font-medium">৳{Number(it.total).toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="space-y-1 ml-auto max-w-xs text-sm">
                <div className="flex justify-between"><span className="text-muted-foreground">{isBn ? "সাবটোটাল" : "Subtotal"}</span><span>৳{Number(viewData.sale.subtotal).toLocaleString()}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">{isBn ? "ডিসকাউন্ট" : "Discount"}</span><span>-৳{Number(viewData.sale.discount).toLocaleString()}</span></div>
                {Number(viewData.sale.expense) > 0 && (
                  <div className="flex justify-between"><span className="text-muted-foreground">{isBn ? "খরচ" : "Expense"}</span><span>৳{Number(viewData.sale.expense).toLocaleString()}</span></div>
                )}
                <div className="flex justify-between font-semibold border-t border-border pt-1"><span>{isBn ? "মোট" : "Total"}</span><span>৳{Number(viewData.sale.total_amount).toLocaleString()}</span></div>
                <div className="flex justify-between text-green-600"><span>{isBn ? "পেইড" : "Paid"}</span><span>৳{Number(viewData.sale.paid_amount).toLocaleString()}</span></div>
                <div className="flex justify-between text-orange-600"><span>{isBn ? "বকেয়া" : "Due"}</span><span>৳{Number(viewData.sale.due_amount).toLocaleString()}</span></div>
              </div>

              {viewData.sale.note && (
                <div className="rounded-lg bg-muted/50 p-3 text-xs">
                  <div className="text-muted-foreground mb-1">{isBn ? "নোট" : "Note"}</div>
                  <div>{viewData.sale.note}</div>
                </div>
              )}

              <div className="flex justify-end gap-2 pt-2">
                <button
                  onClick={() => printOne(viewData.sale.id)}
                  className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:opacity-90"
                >
                  <Printer className="h-4 w-4" />
                  {isBn ? "প্রিন্ট" : "Print"}
                </button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      <AlertDialog open={!!deleteId} onOpenChange={(o) => !o && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{isBn ? "নিশ্চিত?" : "Are you sure?"}</AlertDialogTitle>
            <AlertDialogDescription>
              {isBn ? "এই ইনভয়েস ও সংশ্লিষ্ট আইটেম স্থায়ীভাবে ডিলিট হবে।" : "This invoice and its items will be permanently deleted."}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{isBn ? "বাতিল" : "Cancel"}</AlertDialogCancel>
            <AlertDialogAction onClick={() => deleteId && deleteMut.mutate(deleteId)}>
              {isBn ? "ডিলিট" : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}
