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 { Plus, Trash2, Eye, Pencil } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { SaleStatusDropdown } from "@/components/sales/SaleStatusDropdown";
import { SalePaymentBadge } from "@/components/sales/SalePaymentBadge";
import { SALE_STATUSES, statusLabel } from "@/components/sales/sale-status";

export const Route = createFileRoute("/_authenticated/sales-orders/")({
  head: () => ({
    meta: [
      { title: "Sales Order তালিকা — Niyamah ERP" },
      { name: "description", content: "সকল sales order এর তালিকা" },
    ],
  }),
  component: SalesOrdersListPage,
});

function SalesOrdersListPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const qc = useQueryClient();
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [search, setSearch] = useState("");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");

  const { data: orders = [], isLoading } = useQuery({
    queryKey: ["sales-orders", statusFilter, search, fromDate, toDate],
    queryFn: async () => {
      let q = supabase
        .from("sales_orders" as any)
        .select("*, customers(name, mobile)")
        .order("created_at", { ascending: false });
      if (statusFilter !== "all") q = q.eq("status", statusFilter);
      if (fromDate) q = q.gte("order_date", fromDate);
      if (toDate) q = q.lte("order_date", toDate);
      
      const { data, error } = await q;
      if (error) throw error;
      let rows = (data as any[]) || [];

      // Fetch SR/DSR (created_by → profiles.full_name) separately since no FK
      const userIds = Array.from(new Set(rows.map((r) => r.created_by).filter(Boolean)));
      if (userIds.length > 0) {
        const { data: profs } = await supabase
          .from("profiles")
          .select("id, full_name")
          .in("id", userIds as string[]);
        const m = new Map((profs || []).map((p: any) => [p.id, p.full_name]));
        rows = rows.map((r) => ({ ...r, sr_name: r.created_by ? m.get(r.created_by) : null }));
      }

      if (search.trim()) {
        const s = search.trim().toLowerCase();
        rows = rows.filter((r) =>
          r.order_no?.toLowerCase().includes(s) ||
          r.customers?.name?.toLowerCase().includes(s) ||
          r.customers?.mobile?.includes(s)
        );
      }
      return rows;
    },
  });


  const deleteOrder = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("sales_orders" as any).delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "অর্ডার ডিলিট হয়েছে" : "Order deleted");
      qc.invalidateQueries({ queryKey: ["sales-orders"] });
      setDeleteId(null);
    },
    onError: (e: any) => toast.error(e.message),
  });

  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 ? "Sales Order তালিকা" : "Sales Orders"}</h1>
          <p className="text-sm text-muted-foreground">
            {isBn ? "সকল sales order / quotation" : "All sales orders / quotations"}
          </p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <input
            type="search"
            placeholder={isBn ? "ইনভয়েস/গ্রাহক/মোবাইল" : "Invoice / customer / mobile"}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="rounded-lg border border-border bg-card px-3 py-2 text-sm w-56"
          />
          <input
            type="date"
            value={fromDate}
            onChange={(e) => setFromDate(e.target.value)}
            className="rounded-lg border border-border bg-card px-2 py-2 text-sm"
            title={isBn ? "শুরু" : "From"}
          />
          <input
            type="date"
            value={toDate}
            onChange={(e) => setToDate(e.target.value)}
            className="rounded-lg border border-border bg-card px-2 py-2 text-sm"
            title={isBn ? "শেষ" : "To"}
          />
          <select
            className="rounded-lg border border-border bg-card px-3 py-2 text-sm"
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
          >
            <option value="all">{isBn ? "সকল স্ট্যাটাস" : "All Status"}</option>
            {SALE_STATUSES.map((s) => (
              <option key={s} value={s}>{statusLabel(s, isBn)}</option>
            ))}
          </select>
          <Link
            to="/sales-orders/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 Order"}
          </Link>
        </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 No"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "গ্রাহক" : "Customer"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "তারিখ" : "Date"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "SR/DSR" : "SR/DSR"}</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 ? "অর্ডার স্ট্যাটাস" : "Order Status"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "সেল স্ট্যাটাস" : "Sale Status"}</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>
            ) : orders.length === 0 ? (
              <tr><td colSpan={10} className="px-4 py-8 text-center text-muted-foreground">{isBn ? "কোনো অর্ডার নেই" : "No orders"}</td></tr>
            ) : (
              orders.map((o: any) => (
                <tr key={o.id} className="border-b border-border last:border-0">
                  <td className="px-4 py-3 font-mono text-xs">{o.order_no}</td>
                  <td className="px-4 py-3">
                    <div className="text-foreground">{o.customers?.name || (isBn ? "ওয়াক-ইন" : "Walk-in")}</div>
                    {o.customers?.mobile && <div className="text-xs text-muted-foreground">{o.customers.mobile}</div>}
                  </td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">{o.order_date}</td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">{o.sr_name || "—"}</td>
                  <td className="px-4 py-3 text-right font-semibold">৳{Number(o.total_amount).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-green-600">৳{Number(o.paid_amount).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-orange-600">৳{Number(o.due_amount).toLocaleString()}</td>
                  <td className="px-4 py-3">
                    <SaleStatusDropdown orderId={o.id} current={o.status} />
                  </td>
                  <td className="px-4 py-3">
                    <SalePaymentBadge status={o.sale_status || "draft"} />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-1">
                      <Link
                        to="/sales-orders/$orderId"
                        params={{ orderId: o.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" />
                      </Link>
                      <Link
                        to="/sales-orders/$orderId/edit"
                        params={{ orderId: o.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={() => setDeleteId(o.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>

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