import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { SaleStatusBadge } from "@/components/sales/SaleStatusBadge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Download } from "lucide-react";

export const Route = createFileRoute("/_authenticated/reports/sales-status")({
  head: () => ({
    meta: [{ title: "Sale Status রিপোর্ট — Niyamah ERP" }],
  }),
  component: SalesStatusReportPage,
});

type TabDef = {
  key: string;
  group?: string[];
  saleStatusGroup?: string[];
  payStatusGroup?: string[];
};

const TABS: TabDef[] = [
  { key: "pending", group: ["pending", "confirmed", "processing", "ready_for_delivery"] },
  { key: "delivered", group: ["completed", "delivered", "partial_delivered"] },
  { key: "due", payStatusGroup: ["due", "partial"] },
  { key: "refunded", saleStatusGroup: ["refunded"] },
  { key: "cancelled", group: ["cancelled"] },
  { key: "returned", group: ["returned"] },
];

function exportCsv(rows: any[], filename: string) {
  if (!rows.length) return;
  const headers = Object.keys(rows[0]);
  const csv = [
    headers.join(","),
    ...rows.map((r) => headers.map((h) => JSON.stringify(r[h] ?? "")).join(",")),
  ].join("\n");
  const blob = new Blob([csv], { type: "text/csv" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

function SalesStatusReportPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const [tab, setTab] = useState("pending");
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");

  const tabDef = TABS.find((t) => t.key === tab)!;

  const { data: rows = [], isLoading } = useQuery({
    queryKey: ["sales-status-report", tab, from, to],
    queryFn: async () => {
      let q = supabase
        .from("sales_orders" as any)
        .select("order_no, order_date, status, sale_status, payment_status, total_amount, paid_amount, due_amount, customers(name, mobile)")
        .order("order_date", { ascending: false });
      if (tabDef.group) q = q.in("status", tabDef.group);
      if (tabDef.saleStatusGroup) q = q.in("sale_status", tabDef.saleStatusGroup);
      if (tabDef.payStatusGroup) {
        q = q.in("payment_status", tabDef.payStatusGroup).not("status", "in", "(cancelled,returned)");
      }
      if (from) q = q.gte("order_date", from);
      if (to) q = q.lte("order_date", to);
      const { data, error } = await q;
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const totals = rows.reduce(
    (acc: any, r: any) => {
      acc.total += Number(r.total_amount || 0);
      acc.due += Number(r.due_amount || 0);
      return acc;
    },
    { total: 0, due: 0 }
  );

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{isBn ? "Sale Status রিপোর্ট" : "Sale Status Report"}</h1>
        <p className="text-sm text-muted-foreground">
          {isBn ? "স্ট্যাটাস অনুযায়ী অর্ডার রিপোর্ট" : "Orders grouped by status"}
        </p>
      </div>

      <div className="mb-4 flex flex-wrap items-end gap-3">
        <div>
          <label className="block text-xs text-muted-foreground mb-1">{isBn ? "শুরু" : "From"}</label>
          <input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className="rounded-md border border-border bg-card px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="block text-xs text-muted-foreground mb-1">{isBn ? "শেষ" : "To"}</label>
          <input type="date" value={to} onChange={(e) => setTo(e.target.value)} className="rounded-md border border-border bg-card px-3 py-2 text-sm" />
        </div>
        <button
          onClick={() => exportCsv(rows.map((r: any) => ({
            order_no: r.order_no, date: r.order_date, status: r.status,
            customer: r.customers?.name || "", mobile: r.customers?.mobile || "",
            total: r.total_amount, due: r.due_amount,
          })), `sales-${tab}-${new Date().toISOString().slice(0,10)}.csv`)}
          className="ml-auto flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted"
        >
          <Download className="h-4 w-4" /> CSV
        </button>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="pending">{isBn ? "অপেক্ষমাণ" : "Pending"}</TabsTrigger>
          <TabsTrigger value="delivered">{isBn ? "ডেলিভার্ড" : "Delivered"}</TabsTrigger>
          <TabsTrigger value="due">{isBn ? "বকেয়া" : "Due"}</TabsTrigger>
          <TabsTrigger value="refunded">{isBn ? "রিফান্ড" : "Refunded"}</TabsTrigger>
          <TabsTrigger value="cancelled">{isBn ? "বাতিল" : "Cancelled"}</TabsTrigger>
          <TabsTrigger value="returned">{isBn ? "ফেরত" : "Returned"}</TabsTrigger>
        </TabsList>

        {TABS.map((t) => (
          <TabsContent key={t.key} value={t.key}>
            <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 ? "অর্ডার নং" : "Order No"}</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">{isBn ? "স্ট্যাটাস" : "Status"}</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 ? "বকেয়া" : "Due"}</th>
                  </tr>
                </thead>
                <tbody>
                  {isLoading ? (
                    <tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">{isBn ? "লোড হচ্ছে..." : "Loading..."}</td></tr>
                  ) : rows.length === 0 ? (
                    <tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">{isBn ? "কোনো ডেটা নেই" : "No data"}</td></tr>
                  ) : (
                    rows.map((r: any) => (
                      <tr key={r.order_no} className="border-b border-border last:border-0">
                        <td className="px-4 py-3 font-mono text-xs">{r.order_no}</td>
                        <td className="px-4 py-3 text-xs text-muted-foreground">{r.order_date}</td>
                        <td className="px-4 py-3">{r.customers?.name || "—"}</td>
                        <td className="px-4 py-3"><SaleStatusBadge status={r.status} /></td>
                        <td className="px-4 py-3 text-right font-semibold">৳{Number(r.total_amount).toLocaleString()}</td>
                        <td className="px-4 py-3 text-right text-orange-600">৳{Number(r.due_amount).toLocaleString()}</td>
                      </tr>
                    ))
                  )}
                </tbody>
                {rows.length > 0 && (
                  <tfoot>
                    <tr className="border-t border-border font-semibold">
                      <td colSpan={4} className="px-4 py-3 text-right">{isBn ? "মোট" : "Total"}</td>
                      <td className="px-4 py-3 text-right">৳{totals.total.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right text-orange-600">৳{totals.due.toLocaleString()}</td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </TabsContent>
        ))}
      </Tabs>
    </PageLayout>
  );
}
