import React, { useState, useEffect, useCallback } from 'react';
import { useElections } from '@/hooks/useElections';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Vote, CheckCircle2, Clock, Lock, Loader2, AlertTriangle, RefreshCw } from 'lucide-react';
import { format } from 'date-fns';

export default function ElectionVotingPage({ electionId }) {
  const {
    fetchElection, fetchPositions, fetchAllCandidates,
    getMyVoterRecord, getMyBallot, castBallot, loading
  } = useElections();

  const [election, setElection] = useState(null);
  const [positions, setPositions] = useState([]);
  const [candidates, setCandidates] = useState([]);
  const [voterRecord, setVoterRecord] = useState(null);
  const [selections, setSelections] = useState({}); // { positionId: [candidateId, ...] }
  const [submitted, setSubmitted] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);

  const loadData = useCallback(async () => {
    setPageLoading(true);
    try {
      const [el, pos, cands, voter] = await Promise.all([
        fetchElection(electionId),
        fetchPositions(electionId),
        fetchAllCandidates(electionId),
        getMyVoterRecord(electionId),
      ]);
      setElection(el);
      setPositions(pos);
      setCandidates(cands);
      setVoterRecord(voter);

      if (voter?.has_voted && voter.vote_token) {
        const ballot = await getMyBallot(electionId, voter.vote_token);
        const sels = {};
        ballot.forEach(b => {
          if (!sels[b.position_id]) sels[b.position_id] = [];
          sels[b.position_id].push(b.candidate_id);
        });
        setSelections(sels);
      }
    } finally {
      setPageLoading(false);
    }
  }, [electionId, fetchElection, fetchPositions, fetchAllCandidates, getMyVoterRecord, getMyBallot]);

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

  const handleToggleCandidate = (positionId, candidateId, seatsAvailable) => {
    setSelections(prev => {
      const current = prev[positionId] || [];
      if (current.includes(candidateId)) {
        return { ...prev, [positionId]: current.filter(id => id !== candidateId) };
      }
      if (current.length >= seatsAvailable) {
        return { ...prev, [positionId]: [...current.slice(1), candidateId] };
      }
      return { ...prev, [positionId]: [...current, candidateId] };
    });
  };

  const handleSubmitBallot = async () => {
    if (!voterRecord?.vote_token) return;
    const ballotSelections = [];
    Object.entries(selections).forEach(([posId, candIds]) => {
      (candIds || []).forEach(candId => {
        ballotSelections.push({ position_id: posId, candidate_id: candId });
      });
    });
    const success = await castBallot(electionId, voterRecord.vote_token, ballotSelections);
    if (success) setSubmitted(true);
  };

  const isVotingOpen = election?.status === 'active' &&
    (!election.voting_end || new Date(election.voting_end) > new Date());
  const allPositionsSelected = positions.every(p => (selections[p.id] || []).length > 0);

  if (pageLoading) {
    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>
    );
  }

  if (!election) {
    return (
      <Card className="border-dashed max-w-lg mx-auto mt-8">
        <CardContent className="py-12 text-center">
          <AlertTriangle className="w-10 h-10 mx-auto text-destructive mb-3" />
          <h3 className="font-semibold text-lg">Election Not Found</h3>
        </CardContent>
      </Card>
    );
  }

  if (!voterRecord) {
    return (
      <Card className="border-dashed max-w-lg mx-auto mt-8">
        <CardContent className="py-12 text-center">
          <Lock className="w-10 h-10 mx-auto text-muted-foreground mb-3" />
          <h3 className="font-semibold text-lg">Not Eligible</h3>
          <p className="text-muted-foreground text-sm">You are not listed as an eligible voter.</p>
        </CardContent>
      </Card>
    );
  }

  if (!voterRecord.has_consent) {
    return (
      <Card className="border-dashed max-w-lg mx-auto mt-8">
        <CardContent className="py-12 text-center">
          <AlertTriangle className="w-10 h-10 mx-auto text-amber-500 mb-3" />
          <h3 className="font-semibold text-lg">Electronic Consent Required</h3>
          <p className="text-muted-foreground text-sm">Please contact your association manager.</p>
        </CardContent>
      </Card>
    );
  }

  if (submitted) {
    return (
      <Card className="max-w-lg mx-auto mt-8 border-primary/30">
        <CardContent className="py-12 text-center">
          <CheckCircle2 className="w-16 h-16 mx-auto text-primary mb-4" />
          <h3 className="font-bold text-2xl mb-2">Vote Submitted!</h3>
          <p className="text-muted-foreground mb-1">Your ballot has been securely recorded.</p>
          <p className="text-sm text-muted-foreground">
            {isVotingOpen && 'You may change your vote until the deadline.'}
          </p>
          {isVotingOpen && (
            <Button variant="outline" className="mt-4 gap-2" onClick={() => { setSubmitted(false); loadData(); }}>
              <RefreshCw className="w-4 h-4" /> Change My Vote
            </Button>
          )}
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div className="space-y-2">
        <div className="flex items-center gap-3">
          <Vote className="w-6 h-6 text-primary" />
          <h2 className="text-2xl font-bold">{election.title}</h2>
        </div>
        {election.description && <p className="text-muted-foreground">{election.description}</p>}
        <div className="flex gap-3 text-xs text-muted-foreground">
          {election.voting_end && (
            <span className="flex items-center gap-1">
              <Clock className="w-3 h-3" /> Closes: {format(new Date(election.voting_end), 'MMM d, yyyy h:mm a')}
            </span>
          )}
          {voterRecord.has_voted && <Badge variant="outline" className="text-xs gap-1"><RefreshCw className="w-3 h-3" /> Changing Vote</Badge>}
        </div>
      </div>

      {!isVotingOpen ? (
        <Card className="border-dashed">
          <CardContent className="py-8 text-center">
            <Lock className="w-8 h-8 mx-auto text-muted-foreground mb-2" />
            <p className="text-muted-foreground">Voting is currently closed.</p>
          </CardContent>
        </Card>
      ) : (
        <>
          <ScrollArea className="max-h-[500px]">
            <div className="space-y-4">
              {positions.map(pos => {
                const posCandidates = candidates.filter(c => c.position_id === pos.id);
                const selected = selections[pos.id] || [];
                const seats = pos.seats_available || 1;
                return (
                  <Card key={pos.id}>
                    <CardHeader className="pb-2 pt-4 px-5">
                      <CardTitle className="text-base">{pos.title}</CardTitle>
                      <p className="text-xs text-muted-foreground">
                        Select up to {seats} candidate{seats > 1 ? 's' : ''} — {selected.length}/{seats} selected
                      </p>
                    </CardHeader>
                    <CardContent className="px-5 pb-4 space-y-3">
                      {posCandidates.map(c => {
                        const isChecked = selected.includes(c.id);
                        return (
                          <div
                            key={c.id}
                            className={`flex items-start space-x-3 border rounded-lg p-3 cursor-pointer transition-colors ${isChecked ? 'bg-primary/5 border-primary/30' : 'hover:bg-muted/50'}`}
                            onClick={() => handleToggleCandidate(pos.id, c.id, seats)}
                          >
                            <Checkbox
                              checked={isChecked}
                              onCheckedChange={() => handleToggleCandidate(pos.id, c.id, seats)}
                              className="mt-0.5"
                              id={`c-${c.id}`}
                            />
                            <Label htmlFor={`c-${c.id}`} className="flex-1 cursor-pointer">
                              <span className="font-medium">{c.candidate_name}</span>
                              {c.bio && <p className="text-xs text-muted-foreground mt-0.5">{c.bio}</p>}
                            </Label>
                          </div>
                        );
                      })}
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </ScrollArea>

          <div className="flex justify-end gap-3 pt-2">
            <Button
              onClick={handleSubmitBallot}
              disabled={loading || !allPositionsSelected}
              size="lg"
              className="gap-2"
            >
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Vote className="w-4 h-4" />}
              {voterRecord.has_voted ? 'Update My Vote' : 'Submit Ballot'}
            </Button>
          </div>
          {!allPositionsSelected && (
            <p className="text-xs text-muted-foreground text-center">Please select at least one candidate for every position.</p>
          )}
        </>
      )}
    </div>
  );
}
