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 } from "@tanstack/react-query";
import { Plus, Search } from "lucide-react";
import { useState } from "react";

export const Route = createFileRoute("/_authenticated/purchases/")({
  head: () => ({
    meta: [
      { title: "ক্রয় তালিকা — Niyamah ERP" },
      { name: "description", content: "Purchase list and management" },
    ],
  }),
  component: PurchaseListPage,
});

function PurchaseListPage() {
  const { tr } = useLanguage();
  const [search, setSearch] = useState("");

  const { data: purchases = [], isLoading } = useQuery({
    queryKey: ["purchases"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("purchases")
        .select("*")
        .order("created_at", { ascending: false })
        .limit(100);
      if (error) throw error;
      return data;
    },
  });

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

  const supplierMap = Object.fromEntries(suppliers.map((s: any) => [s.id, s]));

  const filtered = purchases.filter((p: any) => {
    if (!search) return true;
    const s = supplierMap[p.supplier_id];
    const sName = s ? `${s.name} ${s.name_bn}` : "";
    return (
      p.invoice_no?.toLowerCase().includes(search.toLowerCase()) ||
      sName.toLowerCase().includes(search.toLowerCase())
    );
  });

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{tr("purchaseList")}</h1>
        <p className="text-sm text-muted-foreground">{tr("purchaseSubtitle")}</p>
      </div>

      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mb-4">
        <div className="relative w-full sm:w-72">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <input
            className="w-full rounded-lg border border-border bg-card pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/40"
            placeholder={tr("searchPurchase")}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <Link
          to="/purchases/add"
          className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
        >
          <Plus className="h-4 w-4" />
          {tr("addPurchase")}
        </Link>
      </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 bg-muted/40 text-left">
              <th className="px-4 py-3 font-medium">{tr("invoiceNo")}</th>
              <th className="px-4 py-3 font-medium">{tr("supplier")}</th>
              <th className="px-4 py-3 font-medium">{tr("date")}</th>
              <th className="px-4 py-3 font-medium text-right">{tr("total")}</th>
              <th className="px-4 py-3 font-medium text-right">{tr("paidAmount")}</th>
              <th className="px-4 py-3 font-medium text-right">{tr("dueAmount")}</th>
              <th className="px-4 py-3 font-medium">{tr("status")}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">Loading...</td></tr>
            ) : filtered.length === 0 ? (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">{tr("noDataFound")}</td></tr>
            ) : (
              filtered.map((p: any) => {
                const s = supplierMap[p.supplier_id];
                return (
                  <tr key={p.id} className="border-b border-border/50 hover:bg-muted/20">
                    <td className="px-4 py-3 font-mono text-xs">{p.invoice_no || "—"}</td>
                    <td className="px-4 py-3">{s?.name || "—"}</td>
                    <td className="px-4 py-3">{p.purchase_date}</td>
                    <td className="px-4 py-3 text-right font-medium">৳{Number(p.total_amount).toLocaleString()}</td>
                    <td className="px-4 py-3 text-right text-green-600">৳{Number(p.paid_amount).toLocaleString()}</td>
                    <td className="px-4 py-3 text-right text-red-500">৳{Number(p.due_amount).toLocaleString()}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${
                        p.status === "completed" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : "bg-yellow-100 text-yellow-700"
                      }`}>
                        {p.status}
                      </span>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
    </PageLayout>
  );
}
