import { useEffect, useMemo, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Loader2, Search, Users } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";

interface Props {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  onConfirm: (emails: string[]) => void;
}

interface OwnerRow {
  id: string;
  name: string;
  email: string;
  property_address: string | null;
  association_id: string;
  association_name?: string;
}

export default function OwnerEmailPicker({ open, onOpenChange, onConfirm }: Props) {
  const [loading, setLoading] = useState(false);
  const [owners, setOwners] = useState<OwnerRow[]>([]);
  const [associations, setAssociations] = useState<{ id: string; name: string }[]>([]);
  const [search, setSearch] = useState("");
  const [associationId, setAssociationId] = useState<string>("all");
  const [selected, setSelected] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (!open) return;
    setSelected(new Set());
    (async () => {
      setLoading(true);
      const [{ data: ownersData }, { data: assocData }] = await Promise.all([
        supabase
          .from("owners")
          .select("id, first_name, last_name, email, property_address, association_id, status")
          .not("email", "is", null)
          .neq("email", "")
          .order("last_name"),
        supabase.from("associations").select("id, name").order("name"),
      ]);
      const assocMap = new Map((assocData || []).map((a: any) => [a.id, a.name]));
      setAssociations((assocData as any) || []);
      setOwners(
        ((ownersData as any[]) || []).map((o) => ({
          id: o.id,
          name: `${o.first_name || ""} ${o.last_name || ""}`.trim() || "(no name)",
          email: o.email,
          property_address: o.property_address,
          association_id: o.association_id,
          association_name: assocMap.get(o.association_id) || "",
        })),
      );
      setLoading(false);
    })();
  }, [open]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return owners.filter((o) => {
      if (associationId !== "all" && o.association_id !== associationId) return false;
      if (!q) return true;
      return (
        o.name.toLowerCase().includes(q) ||
        o.email.toLowerCase().includes(q) ||
        (o.property_address || "").toLowerCase().includes(q) ||
        (o.association_name || "").toLowerCase().includes(q)
      );
    });
  }, [owners, search, associationId]);

  const toggle = (ownerId: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(ownerId)) next.delete(ownerId);
      else next.add(ownerId);
      return next;
    });
  };

  const allSelected = filtered.length > 0 && filtered.every((o) => selected.has(o.id));
  const toggleAll = () => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (allSelected) filtered.forEach((o) => next.delete(o.id));
      else filtered.forEach((o) => next.add(o.id));
      return next;
    });
  };

  const handleConfirm = () => {
    const emails = owners.filter((owner) => selected.has(owner.id)).map((owner) => owner.email);
    onConfirm(Array.from(new Set(emails.map((email) => email.toLowerCase()))));
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[720px] h-[80vh] flex flex-col p-0 gap-0">
        <DialogHeader className="p-6 pb-3 border-b shrink-0">
          <DialogTitle className="flex items-center gap-2"><Users className="h-5 w-5" /> Select Homeowners</DialogTitle>
          <DialogDescription>Pick recipients from your homeowner roster.</DialogDescription>
        </DialogHeader>

        <div className="p-4 border-b shrink-0 flex flex-col sm:flex-row gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input className="pl-9" placeholder="Search name, email, address..." value={search} onChange={(e) => setSearch(e.target.value)} />
          </div>
          <Select value={associationId} onValueChange={setAssociationId}>
            <SelectTrigger className="sm:w-[240px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Associations</SelectItem>
              {associations.map((a) => (
                <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex-1 min-h-0 overflow-hidden">
          {loading ? (
            <div className="flex items-center justify-center py-12 text-muted-foreground">
              <Loader2 className="h-6 w-6 animate-spin" />
            </div>
          ) : (
            <ScrollArea className="h-full">
              <div className="px-4 py-2 sticky top-0 bg-background border-b flex items-center gap-3 text-sm">
                <Checkbox checked={allSelected} onCheckedChange={toggleAll} />
                <span className="text-muted-foreground">
                  {selected.size} selected · {filtered.length} shown
                </span>
              </div>
              <ul className="divide-y">
                {filtered.map((o) => {
                  const checked = selected.has(o.id);
                  return (
                    <li
                      key={o.id}
                      className="px-4 py-2 flex items-center gap-3 hover:bg-accent cursor-pointer"
                      onClick={() => toggle(o.id)}
                    >
                      <Checkbox
                        checked={checked}
                        onClick={(event) => event.stopPropagation()}
                        onCheckedChange={() => toggle(o.id)}
                      />
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-foreground truncate">{o.name}</span>
                          {o.association_name && (
                            <Badge variant="outline" className="text-xs">{o.association_name}</Badge>
                          )}
                        </div>
                        <div className="text-xs text-muted-foreground truncate">
                          {o.email}{o.property_address ? ` · ${o.property_address}` : ""}
                        </div>
                      </div>
                    </li>
                  );
                })}
                {filtered.length === 0 && (
                  <li className="px-4 py-8 text-center text-sm text-muted-foreground">No homeowners match your filters.</li>
                )}
              </ul>
            </ScrollArea>
          )}
        </div>

        <DialogFooter className="p-4 border-t shrink-0">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleConfirm} disabled={selected.size === 0}>
            Add {selected.size > 0 ? `${selected.size} ` : ""}Recipient{selected.size === 1 ? "" : "s"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
