import { useState, useEffect, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { CheckCircle, Loader2 } from "lucide-react";

interface Props {
  voteId: string;
  voteOptions: string[];
  status: string;
}

export default function BoardVoteOptionsVoting({ voteId, voteOptions, status }: Props) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [responses, setResponses] = useState<any[]>([]);
  const [selectedOption, setSelectedOption] = useState("");
  const [myVote, setMyVote] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);

  const fetchResponses = useCallback(async () => {
    setFetching(true);
    const { data } = await supabase
      .from("board_vote_responses")
      .select("*")
      .eq("board_vote_id", voteId);
    const list = data || [];
    const userIds = Array.from(new Set(list.map((r: any) => r.user_id).filter(Boolean)));
    if (userIds.length > 0) {
      const { data: profs } = await supabase
        .from("profiles")
        .select("id, full_name, email")
        .in("id", userIds);
      const map = new Map((profs || []).map((p: any) => [p.id, p]));
      list.forEach((r: any) => { r.profile = map.get(r.user_id) || null; });
    }
    setResponses(list);
    const mine = list.find((r: any) => r.user_id === user?.id);
    if (mine) setMyVote(mine.vote_option);
    setFetching(false);
  }, [voteId, user?.id]);

  useEffect(() => { fetchResponses(); }, [fetchResponses]);

  const handleSubmit = async () => {
    if (!selectedOption || !user) return;
    setLoading(true);
    const { error } = await supabase
      .from("board_vote_responses")
      .insert({ board_vote_id: voteId, user_id: user.id, vote_option: selectedOption });
    setLoading(false);
    if (error) {
      if (error.code === "23505") {
        toast({ variant: "destructive", title: "Already voted", description: "You have already cast your vote." });
      } else {
        toast({ variant: "destructive", title: "Error", description: error.message });
      }
    } else {
      toast({ title: "Vote submitted" });
      setMyVote(selectedOption);
      fetchResponses();
    }
  };

  const total = responses.length;
  const results = (voteOptions || []).map(opt => {
    const count = responses.filter((r: any) => r.vote_option === opt).length;
    return { option: opt, count, percentage: total > 0 ? Math.round((count / total) * 100) : 0 };
  });

  if (fetching) {
    return <div className="flex justify-center py-4"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>;
  }

  const isOpen = status === "open";
  const hasVoted = !!myVote;
  const winner = !isOpen && results.length > 0
    ? results.reduce((a, b) => (b.count > a.count ? b : a), results[0])
    : null;
  const isTie = winner && results.filter(r => r.count === winner.count).length > 1 && winner.count > 0;

  return (
    <div className="space-y-4 border rounded-lg p-4 bg-muted/20">
      <div className="flex items-center justify-between">
        <h4 className="font-semibold text-sm">Vote Options</h4>
        <Badge variant={isOpen ? "default" : "secondary"}>{total} vote{total !== 1 ? "s" : ""} cast</Badge>
      </div>

      {!isOpen && winner && total > 0 && (
        <div className="rounded-md border border-primary/30 bg-primary/5 p-3 text-sm">
          <span className="font-semibold">Final Result: </span>
          {isTie ? (
            <span>Tie ({winner.count} vote{winner.count !== 1 ? "s" : ""} each)</span>
          ) : (
            <span>{winner.option} wins with {winner.count} vote{winner.count !== 1 ? "s" : ""} ({winner.percentage}%)</span>
          )}
        </div>
      )}

      {/* Results view - always shown */}
      <div className="space-y-2">
        {results.map(r => (
          <div key={r.option} className="space-y-1">
            <div className="flex items-center justify-between text-sm">
              <span className="flex items-center gap-1.5">
                {r.option}
                {myVote === r.option && <CheckCircle className="h-3.5 w-3.5 text-primary" />}
              </span>
              <span className="text-muted-foreground">{r.count} ({r.percentage}%)</span>
            </div>
            <Progress value={r.percentage} className="h-2" />
          </div>
        ))}
      </div>

      {/* Voter list - shown when closed */}
      {!isOpen && responses.length > 0 && (
        <div className="border-t pt-4 space-y-2">
          <h5 className="font-semibold text-sm">Voter List</h5>
          <div className="space-y-1.5">
            {(voteOptions || []).map(opt => {
              const voters = responses.filter((r: any) => r.vote_option === opt);
              if (voters.length === 0) return null;
              return (
                <div key={opt} className="text-sm">
                  <span className="font-medium">{opt}:</span>{" "}
                  <span className="text-muted-foreground">
                    {voters.map((v: any) => v.profile?.full_name || v.profile?.email || "Unknown").join(", ")}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Voting form - only if open and not yet voted */}
      {isOpen && !hasVoted && (
        <div className="border-t pt-4 space-y-3">
          <p className="text-sm text-muted-foreground">Select one option to cast your vote:</p>
          <RadioGroup value={selectedOption} onValueChange={setSelectedOption} className="gap-2">
            {(voteOptions || []).map(opt => (
              <div key={opt} className="flex items-center space-x-2 border rounded-md p-3 hover:bg-muted/50 cursor-pointer">
                <RadioGroupItem value={opt} id={`vote-opt-${opt}`} />
                <Label htmlFor={`vote-opt-${opt}`} className="flex-1 cursor-pointer text-sm">{opt}</Label>
              </div>
            ))}
          </RadioGroup>
          <Button size="sm" onClick={handleSubmit} disabled={loading || !selectedOption}>
            {loading && <Loader2 className="h-4 w-4 mr-2 animate-spin" />} Submit Vote
          </Button>
        </div>
      )}

      {hasVoted && isOpen && (
        <p className="text-sm text-muted-foreground italic">You voted: <span className="font-medium text-foreground">{myVote}</span></p>
      )}
    </div>
  );
}
