import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SelectGroup, SelectLabel } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/contexts/AuthContext";
import { ThumbsUp, ThumbsDown, Loader2, ShieldCheck, Users, Plus, Trash2 } from "lucide-react";

interface Props {
  entityType: string;
  entityId: string;
  associationId?: string | null;
  onRecorded?: () => void;
}

type ArcMember = { user_id: string; full_name: string | null; email: string | null };
type CommitteeMember = { id: string; name: string; email: string | null };

const NAME_ONLY = "__name_only__";
const COMMITTEE_PREFIX = "committee:";

export default function RecordArcMemberVote({ entityType, entityId, associationId, onRecorded }: Props) {
  const { isAdmin, user } = useAuth();
  const { toast } = useToast();
  const [members, setMembers] = useState<ArcMember[]>([]);
  const [committee, setCommittee] = useState<CommitteeMember[]>([]);
  const [selectedUserId, setSelectedUserId] = useState<string>("");
  const [voterName, setVoterName] = useState<string>("");
  const [loading, setLoading] = useState(false);
  const [manageOpen, setManageOpen] = useState(false);
  const [newName, setNewName] = useState("");
  const [newEmail, setNewEmail] = useState("");
  const [adding, setAdding] = useState(false);

  const loadCommittee = async () => {
    if (!associationId) {
      setCommittee([]);
      return;
    }
    const { data } = await supabase
      .from("arc_committee_members")
      .select("id, name, email")
      .eq("association_id", associationId)
      .eq("is_active", true)
      .order("name");
    setCommittee((data ?? []) as CommitteeMember[]);
  };

  useEffect(() => {
    if (!isAdmin) return;
    (async () => {
      const { data: roles } = await supabase
        .from("user_roles")
        .select("user_id")
        .eq("role", "arc_member");
      let ids = [...new Set((roles ?? []).map((r) => r.user_id).filter(Boolean) as string[])];
      if (ids.length && associationId) {
        const [{ data: owners }, { data: boards }] = await Promise.all([
          supabase.from("owners").select("user_id").eq("association_id", associationId).neq("status", "archived").in("user_id", ids),
          supabase.from("board_members").select("user_id").eq("association_id", associationId).in("user_id", ids),
        ]);
        const allowed = new Set<string>([
          ...((owners ?? []).map((o: any) => o.user_id).filter(Boolean)),
          ...((boards ?? []).map((b: any) => b.user_id).filter(Boolean)),
        ]);
        ids = ids.filter((id) => allowed.has(id));
      }
      if (ids.length) {
        const { data: profiles } = await supabase
          .from("profiles")
          .select("user_id, full_name, email")
          .in("user_id", ids);
        setMembers((profiles ?? []) as ArcMember[]);
      } else {
        setMembers([]);
      }
      await loadCommittee();
    })();
  }, [isAdmin, associationId]);

  if (!isAdmin) return null;

  const addCommitteeMember = async () => {
    if (!associationId || !newName.trim()) return;
    setAdding(true);
    try {
      const { error } = await supabase.from("arc_committee_members").insert({
        association_id: associationId,
        name: newName.trim(),
        email: newEmail.trim() || null,
        created_by: user?.id ?? null,
      });
      if (error) throw error;
      setNewName("");
      setNewEmail("");
      await loadCommittee();
      toast({ title: "Committee member added" });
    } catch (err: any) {
      toast({ title: "Error", description: err.message, variant: "destructive" });
    } finally {
      setAdding(false);
    }
  };

  const removeCommitteeMember = async (id: string) => {
    const { error } = await supabase.from("arc_committee_members").delete().eq("id", id);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
      return;
    }
    await loadCommittee();
  };

  const submit = async (vote: "approve" | "deny") => {
    if (!selectedUserId) {
      toast({ title: "Select a member", description: "Choose an ARC member or enter a name.", variant: "destructive" });
      return;
    }
    const isNameOnly = selectedUserId === NAME_ONLY;
    const isCommittee = selectedUserId.startsWith(COMMITTEE_PREFIX);
    if (isNameOnly && !voterName.trim()) {
      toast({ title: "Enter a name", description: "Provide the voter's name.", variant: "destructive" });
      return;
    }
    setLoading(true);
    try {
      const payload: any = {
        entity_type: entityType,
        entity_id: entityId,
        vote,
        recorded_by: user?.id ?? null,
      };
      let resolvedName = "";
      if (isNameOnly) {
        resolvedName = voterName.trim();
      } else if (isCommittee) {
        const id = selectedUserId.slice(COMMITTEE_PREFIX.length);
        resolvedName = committee.find((c) => c.id === id)?.name || "Committee Member";
      }

      if (isNameOnly || isCommittee) {
        payload.user_id = null;
        payload.voter_name = resolvedName;
        await supabase
          .from("entity_votes")
          .delete()
          .eq("entity_type", entityType)
          .eq("entity_id", entityId)
          .is("user_id", null)
          .ilike("voter_name", resolvedName);
        const { error } = await supabase.from("entity_votes").insert(payload);
        if (error) throw error;
      } else {
        payload.user_id = selectedUserId;
        const { error } = await supabase
          .from("entity_votes")
          .upsert(payload, { onConflict: "entity_type,entity_id,user_id" });
        if (error) throw error;
      }
      const member = members.find((m) => m.user_id === selectedUserId);
      const label = resolvedName || member?.full_name || member?.email || "Member";
      toast({ title: "Vote recorded", description: `${label}: ${vote}` });
      onRecorded?.();
    } catch (err: any) {
      toast({ title: "Error", description: err.message, variant: "destructive" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="rounded-lg border bg-muted/30 p-3 space-y-2">
      <div className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground flex items-center justify-between gap-2">
        <span className="flex items-center gap-1.5">
          <ShieldCheck className="h-3.5 w-3.5" /> Admin: Record vote on behalf of ARC member
        </span>
        {associationId && (
          <Dialog open={manageOpen} onOpenChange={setManageOpen}>
            <DialogTrigger asChild>
              <Button size="sm" variant="ghost" className="h-7 gap-1 text-[11px]">
                <Users className="h-3.5 w-3.5" /> Manage Committee
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>ARC Committee Members</DialogTitle>
                <DialogDescription>
                  Add committee members for this association. They don't need accounts — use them to record historical votes.
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-2 max-h-[300px] overflow-y-auto">
                {committee.length === 0 ? (
                  <p className="text-xs text-muted-foreground py-2">No committee members yet.</p>
                ) : (
                  committee.map((c) => (
                    <div key={c.id} className="flex items-center justify-between rounded border bg-card px-3 py-2">
                      <div>
                        <p className="text-sm font-medium">{c.name}</p>
                        {c.email && <p className="text-xs text-muted-foreground">{c.email}</p>}
                      </div>
                      <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => removeCommitteeMember(c.id)}>
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  ))
                )}
              </div>
              <div className="space-y-2 border-t pt-3">
                <Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Member name *" />
                <Input value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder="Email (optional)" />
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setManageOpen(false)}>Close</Button>
                <Button onClick={addCommitteeMember} disabled={adding || !newName.trim()} className="gap-1">
                  <Plus className="h-3.5 w-3.5" /> {adding ? "Adding…" : "Add Member"}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        )}
      </div>
      <div className="flex flex-wrap items-center gap-2">
        <Select value={selectedUserId} onValueChange={setSelectedUserId}>
          <SelectTrigger className="h-8 text-xs w-[240px]">
            <SelectValue placeholder="Select ARC member..." />
          </SelectTrigger>
          <SelectContent>
            {members.length > 0 && (
              <SelectGroup>
                <SelectLabel className="text-[10px]">Users</SelectLabel>
                {members.map((m) => (
                  <SelectItem key={m.user_id} value={m.user_id} className="text-xs">
                    {m.full_name || m.email || m.user_id.slice(0, 8)}
                  </SelectItem>
                ))}
              </SelectGroup>
            )}
            {committee.length > 0 && (
              <SelectGroup>
                <SelectLabel className="text-[10px]">Committee Roster</SelectLabel>
                {committee.map((c) => (
                  <SelectItem key={c.id} value={`${COMMITTEE_PREFIX}${c.id}`} className="text-xs">
                    {c.name}{c.email ? ` (${c.email})` : ""}
                  </SelectItem>
                ))}
              </SelectGroup>
            )}
            <SelectItem value={NAME_ONLY} className="text-xs">
              + Enter name (one-time)
            </SelectItem>
          </SelectContent>
        </Select>
        {selectedUserId === NAME_ONLY && (
          <Input
            value={voterName}
            onChange={(e) => setVoterName(e.target.value)}
            placeholder="Voter name"
            className="h-8 text-xs w-[180px]"
          />
        )}
        <Button size="sm" variant="outline" disabled={loading || !selectedUserId} onClick={() => submit("approve")} className="gap-1 h-8">
          {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ThumbsUp className="h-3.5 w-3.5" />} Approve
        </Button>
        <Button size="sm" variant="outline" disabled={loading || !selectedUserId} onClick={() => submit("deny")} className="gap-1 h-8">
          {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ThumbsDown className="h-3.5 w-3.5" />} Deny
        </Button>
      </div>
      {members.length === 0 && committee.length === 0 && selectedUserId !== NAME_ONLY && (
        <p className="text-xs text-muted-foreground">
          No ARC members yet — click <strong>Manage Committee</strong> to add members for this association, or use "Enter name" for a one-time vote.
        </p>
      )}
    </div>
  );
}
