import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { accounting } from "@/lib/accountingClient";
import { useCompanyId } from "./lib/useCompanyId";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Plus, Search, Trash2, MoreHorizontal, ThumbsUp, ThumbsDown, FileSpreadsheet, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { money, fmtDate } from "./lib/format";
import { DocumentForm } from "./components/DocumentForm";
import { StatusBadge } from "./components/StatusBadge";
import { EmptyState } from "./components/EmptyState";

const RANGES = [
  { value: "all", label: "All time" },
  { value: "30", label: "Last 30 days" },
  { value: "90", label: "Last 90 days" },
  { value: "year", label: "This year" },
];

export default function AccountingEstimatesPage() {
  const { companyId, loading: companyLoading, error: companyError, associationId, associationName } = useCompanyId();
  const cid = companyId ?? "";
  const cur = "USD";
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [range, setRange] = useState("all");

  const { data: estimates = [], isLoading } = useQuery({
    queryKey: ["estimates", cid],
    enabled: !!cid,
    queryFn: async () => {
      const { data } = await accounting
        .from("estimates").select("*, customers(name)")
        .eq("company_id", cid).order("issue_date", { ascending: false });
      return (data as any[]) ?? [];
    },
  });

  const { data: customers = [] } = useQuery({
    queryKey: ["customers-lookup", cid],
    enabled: !!cid,
    queryFn: async () => (await accounting.from("customers").select("id,name").eq("company_id", cid).order("name")).data ?? [],
  });

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    const now = new Date();
    let cutoff: Date | null = null;
    if (range === "30") cutoff = new Date(now.getTime() - 30 * 86400000);
    else if (range === "90") cutoff = new Date(now.getTime() - 90 * 86400000);
    else if (range === "year") cutoff = new Date(now.getFullYear(), 0, 1);
    return (estimates as any[]).filter((e: any) => {
      if (statusFilter !== "all" && e.status !== statusFilter) return false;
      if (cutoff && new Date(e.issue_date) < cutoff) return false;
      if (q) {
        const hay = `${e.number} ${e.customers?.name ?? ""}`.toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
  }, [estimates, search, statusFilter, range]);

  const save = async (v: any) => {
    if (!v.number.trim()) return toast.error("Estimate number required");
    if (v.items.some((i: any) => !i.description.trim())) return toast.error("All items need a description");
    const { data: est, error } = await accounting.from("estimates").insert({
      company_id: cid,
      customer_id: v.customerId || null,
      number: v.number,
      issue_date: v.issueDate,
      expiry_date: v.dueDate || null,
      subtotal: v.subtotal, tax: v.tax, total: v.total,
      notes: v.notes || null,
      status: v.status,
    } as any).select().single();
    if (error || !est) return toast.error(error?.message ?? "Failed");
    const rows = v.items.map((it: any) => ({
      estimate_id: (est as any).id,
      description: it.description,
      quantity: it.quantity,
      rate: it.rate,
      amount: +(it.quantity * it.rate * (1 + it.taxPct / 100)).toFixed(2),
    }));
    await accounting.from("estimate_items").insert(rows as any);
    toast.success(v.status === "draft" ? "Draft saved" : "Estimate sent");
    setOpen(false);
    qc.invalidateQueries({ queryKey: ["estimates", cid] });
  };

  const setStatus = async (id: string, status: string) => {
    const { error } = await accounting.from("estimates").update({ status } as any).eq("id", id);
    if (error) return toast.error(error.message);
    qc.invalidateQueries({ queryKey: ["estimates", cid] });
  };

  const remove = async (id: string) => {
    const { error } = await accounting.from("estimates").delete().eq("id", id);
    if (error) return toast.error(error.message);
    qc.invalidateQueries({ queryKey: ["estimates", cid] });
  };

  if (!associationId) return <p className="text-sm text-muted-foreground">Select an association.</p>;
  if (companyLoading) return <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
  if (companyError || !companyId) return <p className="text-sm text-muted-foreground text-center py-12">{companyError || "Accounting setup is not ready."}</p>;

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Estimates</h1>
          <p className="text-sm text-muted-foreground">{filtered.length} of {(estimates as any[]).length}</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button className="bg-emerald-600 hover:bg-emerald-700 text-white">
              <Plus className="mr-1 h-4 w-4" /> New Estimate
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-4xl">
            <DialogHeader><DialogTitle>New Estimate</DialogTitle></DialogHeader>
            <DocumentForm
              kind="Estimate"
              numberPrefix="EST"
              customers={customers as any}
              currency={cur}
              companyName={associationName ?? ""}
              dueDateLabel="Expiry Date"
              draftStatus="draft"
              sentStatus="sent"
              onSubmit={save}
              onClose={() => setOpen(false)}
            />
          </DialogContent>
        </Dialog>
      </div>

      <Card className="border-border/60 shadow-sm">
        <CardContent className="p-4">
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative min-w-[220px] flex-1">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input placeholder="Search estimate # or customer…" className="h-9 pl-9"
                value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="h-9 w-[160px]"><SelectValue placeholder="Status" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All statuses</SelectItem>
                <SelectItem value="draft">Draft</SelectItem>
                <SelectItem value="sent">Sent</SelectItem>
                <SelectItem value="accepted">Accepted</SelectItem>
                <SelectItem value="declined">Declined</SelectItem>
              </SelectContent>
            </Select>
            <Select value={range} onValueChange={setRange}>
              <SelectTrigger className="h-9 w-[160px]"><SelectValue placeholder="Date range" /></SelectTrigger>
              <SelectContent>
                {RANGES.map((r) => <SelectItem key={r.value} value={r.value}>{r.label}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <Card className="border-border/60 shadow-sm">
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
                <tr>
                  <th className="px-6 py-3 text-left font-medium">Estimate #</th>
                  <th className="px-6 py-3 text-left font-medium">Customer</th>
                  <th className="px-6 py-3 text-left font-medium">Date</th>
                  <th className="px-6 py-3 text-left font-medium">Expiry Date</th>
                  <th className="px-6 py-3 text-right font-medium">Amount</th>
                  <th className="px-6 py-3 text-left font-medium">Status</th>
                  <th className="w-10" />
                </tr>
              </thead>
              <tbody className="divide-y divide-border/60">
                {isLoading && Array.from({ length: 5 }).map((_, r) => (
                  <tr key={`sk-${r}`}>
                    {Array.from({ length: 7 }).map((_, c) => (
                      <td key={c} className="px-6 py-3"><div className="h-4 rounded bg-muted animate-pulse" style={{ width: `${40 + ((r * 13 + c * 17) % 50)}%` }} /></td>
                    ))}
                  </tr>
                ))}
                {!isLoading && filtered.map((e: any) => (
                  <tr key={e.id}>
                    <td className="px-6 py-3 font-medium">{e.number}</td>
                    <td className="px-6 py-3">{e.customers?.name ?? "—"}</td>
                    <td className="px-6 py-3 text-muted-foreground">{fmtDate(e.issue_date)}</td>
                    <td className="px-6 py-3 text-muted-foreground">{fmtDate(e.expiry_date)}</td>
                    <td className="px-6 py-3 text-right font-semibold tabular-nums">{money(e.total, cur)}</td>
                    <td className="px-6 py-3"><StatusBadge status={e.status} /></td>
                    <td className="px-2 py-3">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          {e.status === "draft" && (
                            <DropdownMenuItem onClick={() => setStatus(e.id, "sent")}>Mark as Sent</DropdownMenuItem>
                          )}
                          {e.status !== "accepted" && (
                            <DropdownMenuItem onClick={() => setStatus(e.id, "accepted")}>
                              <ThumbsUp className="mr-2 h-4 w-4" /> Mark Accepted
                            </DropdownMenuItem>
                          )}
                          {e.status !== "declined" && (
                            <DropdownMenuItem onClick={() => setStatus(e.id, "declined")}>
                              <ThumbsDown className="mr-2 h-4 w-4" /> Mark Declined
                            </DropdownMenuItem>
                          )}
                          <DropdownMenuItem className="text-red-600" onClick={() => remove(e.id)}>
                            <Trash2 className="mr-2 h-4 w-4" /> Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))}
                {!isLoading && filtered.length === 0 && (
                  <tr><td colSpan={7} className="p-0">
                    <EmptyState icon={FileSpreadsheet} title="No estimates yet" description="Send a quote before turning it into an invoice." />
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
