import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Users, Plus, Search, MoreHorizontal, Edit, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";

export default function ClientInfoPage() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  const fetchData = async () => { setLoading(true); const { data } = await supabase.from("associations").select("*").neq("status", "archived").order("name"); setAssociations(data || []); setLoading(false); };
  useEffect(() => { fetchData(); }, []);
  const filtered = associations.filter((a) => a.name.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-6">
      <div><h1 className="text-2xl font-bold text-foreground flex items-center gap-2"><Users className="h-6 w-6 text-primary" /> Client Info</h1><p className="text-sm text-muted-foreground mt-1">View association details and contacts.</p></div>
      <div className="relative max-w-md"><Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input placeholder="Search..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} /></div>
      {loading ? <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> : filtered.length === 0 ? <Card><CardContent className="py-12 text-center text-muted-foreground">No associations found.</CardContent></Card> : (
        <Card><Table><TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Address</TableHead><TableHead>City</TableHead><TableHead>Phone</TableHead><TableHead>Email</TableHead></TableRow></TableHeader><TableBody>
          {filtered.map((a) => (<TableRow key={a.id}><TableCell className="font-medium">{a.name}</TableCell><TableCell>{a.address || "—"}</TableCell><TableCell>{a.city || "—"}{a.state ? `, ${a.state}` : ""}</TableCell><TableCell>{a.phone || "—"}</TableCell><TableCell>{a.email || "—"}</TableCell></TableRow>))}</TableBody></Table></Card>
      )}
    </div>
  );
}
