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 { useState } from "react";
import { toast } from "sonner";
import { Search, Plus, Eye, Edit2, Trash2, Loader2 } from "lucide-react";

export const Route = createFileRoute("/_authenticated/suppliers/")({
  head: () => ({
    meta: [{ title: "Supplier List — Niyamah ERP" }],
  }),
  component: SupplierListPage,
});

function SupplierListPage() {
  const { tr } = useLanguage();
  const queryClient = useQueryClient();
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState<"all" | "due" | "active" | "inactive">("all");

  const { data: suppliers = [], isLoading } = useQuery({
    queryKey: ["suppliers", search, filter],
    queryFn: async () => {
      let query = supabase
        .from("suppliers")
        .select("*")
        .eq("is_deleted", false)
        .order("created_at", { ascending: false });

      if (search) {
        query = query.or(`name.ilike.%${search}%,mobile.ilike.%${search}%,company_name.ilike.%${search}%`);
      }
      if (filter === "due") {
        query = query.gt("current_due", 0);
      } else if (filter === "active") {
        query = query.eq("status", "active");
      } else if (filter === "inactive") {
        query = query.eq("status", "inactive");
      }

      const { data, error } = await query.limit(100);
      if (error) throw error;
      return data as any[];
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("suppliers").update({ is_deleted: true }).eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("supplierDeleted"));
      queryClient.invalidateQueries({ queryKey: ["suppliers"] });
    },
    onError: (err: any) => toast.error(err.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 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl font-bold text-foreground">{tr("supplierList")}</h1>
          <p className="text-sm text-muted-foreground">{tr("suppliers")}</p>
        </div>
        <Link
          to="/suppliers/add"
          className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90"
        >
          <Plus className="h-4 w-4" /> {tr("addSupplier")}
        </Link>
      </div>

      {/* Search & Filter */}
      <div className="mb-4 flex flex-col gap-3 sm:flex-row">
        <div className="relative flex-1">
          <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={tr("searchSupplier")}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <select
          className={`${inputCls} w-auto min-w-[140px]`}
          value={filter}
          onChange={(e) => setFilter(e.target.value as any)}
        >
          <option value="all">{tr("allSuppliers")}</option>
          <option value="due">{tr("dueSuppliers")}</option>
          <option value="active">{tr("active")}</option>
          <option value="inactive">{tr("inactive")}</option>
        </select>
      </div>

      {/* Table */}
      <div className="rounded-xl border border-border bg-card overflow-x-auto">
        {isLoading ? (
          <div className="flex h-40 items-center justify-center">
            <Loader2 className="h-6 w-6 animate-spin text-primary" />
          </div>
        ) : suppliers.length === 0 ? (
          <div className="flex h-40 items-center justify-center text-muted-foreground text-sm">
            {tr("noData")}
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left">
                <th className="px-4 py-3 font-medium">{tr("supplierName")}</th>
                <th className="px-4 py-3 font-medium">{tr("mobile")}</th>
                <th className="px-4 py-3 font-medium">{tr("companyName")}</th>
                <th className="px-4 py-3 font-medium text-right">{tr("totalPurchase")}</th>
                <th className="px-4 py-3 font-medium text-right">{tr("totalPaid")}</th>
                <th className="px-4 py-3 font-medium text-right">{tr("currentDue")}</th>
                <th className="px-4 py-3 font-medium">{tr("status")}</th>
                <th className="px-4 py-3 font-medium text-center">{tr("action")}</th>
              </tr>
            </thead>
            <tbody>
              {suppliers.map((s: any) => (
                <tr key={s.id} className="border-b border-border/30 hover:bg-muted/30">
                  <td className="px-4 py-3 font-medium">{s.name}</td>
                  <td className="px-4 py-3">{s.mobile}</td>
                  <td className="px-4 py-3">{s.company_name || "—"}</td>
                  <td className="px-4 py-3 text-right">৳{Number(s.total_purchase).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right">৳{Number(s.total_paid).toLocaleString()}</td>
                  <td className={`px-4 py-3 text-right font-semibold ${Number(s.current_due) > 0 ? "text-red-500" : "text-green-500"}`}>
                    ৳{Number(s.current_due).toLocaleString()}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${
                      s.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
                    }`}>
                      {s.status === "active" ? tr("active") : tr("inactive")}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-center gap-2">
                      <Link to="/suppliers/$supplierId" params={{ supplierId: s.id }} className="text-primary hover:text-primary/80">
                        <Eye className="h-4 w-4" />
                      </Link>
                      <Link to="/suppliers/$supplierId/edit" params={{ supplierId: s.id }} className="text-blue-500 hover:text-blue-700">
                        <Edit2 className="h-4 w-4" />
                      </Link>
                      <button
                        onClick={() => {
                          if (confirm(tr("confirmDelete"))) deleteMutation.mutate(s.id);
                        }}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </PageLayout>
  );
}
