import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link } from "react-router-dom";
import { accounting } from "@/lib/accountingClient";
import { useCompanyId } from "./lib/useCompanyId";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table";
import { Plus, Trash2, Home, Search, Users, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { money } from "./lib/format";
import { EmptyState } from "./components/EmptyState";
import { TableSkeleton } from "./components/TableSkeleton";
import { mergeHomeownersByAddress } from "./lib/mergeHomeowners";

const EMPTY_FORM = {
  name: "",
  email: "",
  phone: "",
  account_number: "",
  unit_id: "",
  property_address: "",
  lot_number: "",
  unit_number: "",
  mailing_address: "",
  move_in_date: "",
};

export default function AccountingCustomersPage() {
  const { companyId, loading: companyLoading, error: companyError, associationId } = useCompanyId();
  const cid = companyId ?? "";
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState(EMPTY_FORM);
  const [search, setSearch] = useState("");
  const [merging, setMerging] = useState(false);

  // Fold same-address homeowners into one record. Runs automatically after an
  // add (silent) and on demand from the toolbar button.
  const runMerge = async (silent = false) => {
    if (!cid) return;
    setMerging(true);
    try {
      const r = await mergeHomeownersByAddress(cid);
      if (!silent) {
        if (r.mergedRecords > 0)
          toast.success(`Merged ${r.mergedRecords} duplicate${r.mergedRecords !== 1 ? "s" : ""} across ${r.mergedGroups} address${r.mergedGroups !== 1 ? "es" : ""}`);
        else toast.info("No same-address duplicates found");
      }
      qc.invalidateQueries({ queryKey: ["customers", cid] });
    } catch (e) {
      if (!silent) toast.error(e instanceof Error ? e.message : "Merge failed");
    } finally {
      setMerging(false);
    }
  };

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

  const filtered = (homeowners as any[]).filter((h: any) => {
    const q = search.toLowerCase();
    return (
      h.name?.toLowerCase().includes(q) ||
      h.property_address?.toLowerCase().includes(q) ||
      h.lot_number?.toLowerCase().includes(q) ||
      h.account_number?.toLowerCase().includes(q) ||
      h.unit_id?.toLowerCase().includes(q) ||
      h.email?.toLowerCase().includes(q)
    );
  });

  const save = async () => {
    if (!form.name.trim()) return toast.error("Name required");
    const { error } = await accounting.from("customers").insert({
      name: form.name,
      email: form.email || null,
      phone: form.phone || null,
      account_number: form.account_number.trim() || null,
      unit_id: form.unit_id.trim() || null,
      property_address: form.property_address || null,
      lot_number: form.lot_number || null,
      unit_number: form.unit_number || null,
      mailing_address: form.mailing_address || null,
      move_in_date: form.move_in_date || null,
      billing_address: form.mailing_address || form.property_address || null,
      company_id: cid,
    });
    if (error) return toast.error(error.message);
    toast.success("Homeowner added");
    setForm(EMPTY_FORM);
    setOpen(false);
    qc.invalidateQueries({ queryKey: ["customers", cid] });
    // Auto-merge: if this address already existed, fold the records together
    runMerge(true);
  };

  const remove = async (id: string) => {
    const { error } = await accounting.from("customers").delete().eq("id", id);
    if (error) return toast.error(error.message);
    qc.invalidateQueries({ queryKey: ["customers", 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 items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold">Homeowners</h1>
          <p className="text-sm text-muted-foreground mt-0.5">Manage homeowner accounts, contact info, and ledgers</p>
        </div>
        <div className="flex gap-2">
        <Button variant="outline" onClick={() => runMerge(false)} disabled={merging} title="Merge homeowners that share the same property address">
          {merging ? <Loader2 className="mr-1 h-4 w-4 animate-spin" /> : <Users className="mr-1 h-4 w-4" />} Merge duplicates
        </Button>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-1 h-4 w-4" /> New homeowner</Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader><DialogTitle>New homeowner</DialogTitle></DialogHeader>
            <div className="grid grid-cols-2 gap-3">
              <div className="col-span-2">
                <Label>Full name *</Label>
                <Input maxLength={120} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Jane Smith" />
              </div>
              <div>
                <Label>Email</Label>
                <Input type="email" maxLength={255} value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="jane@example.com" />
              </div>
              <div>
                <Label>Phone</Label>
                <Input maxLength={40} value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="(555) 000-0000" />
              </div>
              <div>
                <Label>Account number</Label>
                <Input maxLength={40} value={form.account_number} onChange={(e) => setForm({ ...form, account_number: e.target.value })} placeholder="ACC-1001" />
              </div>
              <div>
                <Label>Unit ID</Label>
                <Input maxLength={40} value={form.unit_id} onChange={(e) => setForm({ ...form, unit_id: e.target.value })} placeholder="U-042" />
              </div>
              <div className="col-span-2">
                <Label>Property address</Label>
                <Input maxLength={255} value={form.property_address} onChange={(e) => setForm({ ...form, property_address: e.target.value })} placeholder="123 Oak Lane" />
              </div>
              <div>
                <Label>Lot number</Label>
                <Input maxLength={40} value={form.lot_number} onChange={(e) => setForm({ ...form, lot_number: e.target.value })} placeholder="Lot 42" />
              </div>
              <div>
                <Label>Unit / Apt</Label>
                <Input maxLength={40} value={form.unit_number} onChange={(e) => setForm({ ...form, unit_number: e.target.value })} placeholder="Unit 3B" />
              </div>
              <div className="col-span-2">
                <Label>Mailing address <span className="text-muted-foreground text-xs">(if different from property)</span></Label>
                <Input maxLength={255} value={form.mailing_address} onChange={(e) => setForm({ ...form, mailing_address: e.target.value })} placeholder="PO Box or alternate address" />
              </div>
              <div>
                <Label>Move-in date</Label>
                <Input type="date" value={form.move_in_date} onChange={(e) => setForm({ ...form, move_in_date: e.target.value })} />
              </div>
            </div>
            <DialogFooter><Button onClick={save}>Save homeowner</Button></DialogFooter>
          </DialogContent>
        </Dialog>
        </div>
      </div>

      <div className="relative max-w-sm">
        <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          className="pl-9"
          placeholder="Search by name, account #, unit, property, lot, or email…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{filtered.length} homeowner{filtered.length !== 1 ? "s" : ""}</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {isLoading ? (
            <TableSkeleton columns={8} />
          ) : filtered.length === 0 ? (
            <EmptyState icon={Home} title="No homeowners yet" description="Add your first homeowner to get started." />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Account #</TableHead>
                  <TableHead>Property</TableHead>
                  <TableHead>Lot</TableHead>
                  <TableHead>Email</TableHead>
                  <TableHead>Phone</TableHead>
                  <TableHead className="text-right">Balance</TableHead>
                  <TableHead></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.map((h: any) => (
                  <TableRow key={h.id} className="hover:bg-muted/50">
                    <TableCell className="font-medium">
                      <Link to={`/dashboard/accounting/customers/${h.id}`} className="hover:underline">
                        {h.name}
                      </Link>
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {h.account_number ?? "—"}
                      {h.unit_id ? ` · ${h.unit_id}` : ""}
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {h.property_address ?? "—"}
                      {h.unit_number ? `, ${h.unit_number}` : ""}
                    </TableCell>
                    <TableCell className="text-muted-foreground">{h.lot_number ?? "—"}</TableCell>
                    <TableCell>{h.email ?? "—"}</TableCell>
                    <TableCell>{h.phone ?? "—"}</TableCell>
                    <TableCell className="text-right">{money(h.balance, "USD")}</TableCell>
                    <TableCell>
                      <Button
                        size="icon"
                        variant="ghost"
                        onClick={(e) => { e.stopPropagation(); remove(h.id); }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
