import { useEffect, useMemo, useState } from "react";
import { Mail, Phone, Search, Users } from "lucide-react";
import { useBoardAssociations } from "@/contexts/BoardAssociationContext";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

type OwnerRosterRow = {
  id: string;
  first_name: string | null;
  last_name: string | null;
  email: string | null;
  phone: string | null;
  property_address: string | null;
};

export default function BoardOwnerRosterPage() {
  const { associationIds, loading: associationLoading } = useBoardAssociations();
  const [owners, setOwners] = useState<OwnerRosterRow[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (associationLoading) return;
    if (associationIds.length === 0) {
      setOwners([]);
      setLoading(false);
      return;
    }

    setLoading(true);
    (supabase as any)
      .from("owners")
      .select("id, first_name, last_name, email, phone, property_address")
      .in("association_id", associationIds)
      .eq("status", "active")
      .order("property_address", { ascending: true })
      .then(({ data }: { data: OwnerRosterRow[] | null }) => {
        setOwners(data || []);
        setLoading(false);
      });
  }, [associationIds, associationLoading]);

  const filteredOwners = useMemo(() => {
    const query = search.trim().toLowerCase();
    if (!query) return owners;
    return owners.filter((owner) =>
      [owner.property_address, owner.first_name, owner.last_name, owner.email, owner.phone]
        .filter(Boolean)
        .join(" ")
        .toLowerCase()
        .includes(query)
    );
  }, [owners, search]);

  if (associationLoading || loading) {
    return <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Owner Roster</h1>
          <p className="mt-1 text-muted-foreground">Property addresses, owner names, and contact information for your association.</p>
        </div>
        <div className="relative w-full md:w-80">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Search roster" className="pl-9" />
        </div>
      </div>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-base"><Users className="h-4 w-4" /> Owners</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-hidden rounded-md border border-border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Property Address</TableHead>
                  <TableHead>Owner Name</TableHead>
                  <TableHead>Contact Information</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredOwners.map((owner) => {
                  const ownerName = [owner.first_name, owner.last_name].filter(Boolean).join(" ") || "—";
                  return (
                    <TableRow key={owner.id}>
                      <TableCell className="font-medium">{owner.property_address || "—"}</TableCell>
                      <TableCell>{ownerName}</TableCell>
                      <TableCell>
                        <div className="space-y-1 text-sm">
                          {owner.email && <div className="flex items-center gap-2"><Mail className="h-3.5 w-3.5 text-muted-foreground" /> {owner.email}</div>}
                          {owner.phone && <div className="flex items-center gap-2"><Phone className="h-3.5 w-3.5 text-muted-foreground" /> {owner.phone}</div>}
                          {!owner.email && !owner.phone && <span className="text-muted-foreground">—</span>}
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })}
                {filteredOwners.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={3} className="py-8 text-center text-muted-foreground">No owners found.</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}