import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Separator } from '@/components/ui/separator';
import { Keyboard, RotateCcw, CheckCircle2, Minus, Plus } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

const QWERTY_KEYS = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
  'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
  'Z', 'X', 'C', 'V', 'B', 'N', 'M'];

export default function ElectionTallyCounter({ election, positions, candidates, onCertify }) {
  const { toast } = useToast();
  const containerRef = useRef(null);
  const [tallies, setTallies] = useState({});
  const [keyMap, setKeyMap] = useState({});
  const [isActive, setIsActive] = useState(false);
  const [lastAction, setLastAction] = useState(null);

  // Build key assignments on mount
  useEffect(() => {
    const map = {};
    const initialTallies = {};
    let keyIdx = 0;

    positions.forEach(pos => {
      const posCandidates = candidates.filter(c => c.position_id === pos.id);
      posCandidates.forEach(c => {
        if (keyIdx < QWERTY_KEYS.length) {
          map[QWERTY_KEYS[keyIdx]] = { candidateId: c.id, candidateName: c.candidate_name, positionId: pos.id, positionTitle: pos.title };
          keyIdx++;
        }
        initialTallies[c.id] = 0;
      });
    });

    setKeyMap(map);
    setTallies(initialTallies);
  }, [positions, candidates]);

  // Keyboard listener
  const handleKeyDown = useCallback((e) => {
    if (!isActive) return;
    // Ignore if user is typing in an input
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;

    const key = e.key.toUpperCase();
    if (keyMap[key]) {
      e.preventDefault();
      const entry = keyMap[key];
      setTallies(prev => ({ ...prev, [entry.candidateId]: (prev[entry.candidateId] || 0) + 1 }));
      setLastAction({ key, name: entry.candidateName, time: Date.now() });
    }
  }, [isActive, keyMap]);

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  const incrementTally = (candidateId) => {
    setTallies(prev => ({ ...prev, [candidateId]: (prev[candidateId] || 0) + 1 }));
  };

  const decrementTally = (candidateId) => {
    setTallies(prev => ({ ...prev, [candidateId]: Math.max(0, (prev[candidateId] || 0) - 1) }));
  };

  const resetTallies = () => {
    if (!confirm('Reset all tallies to zero?')) return;
    const reset = {};
    Object.keys(tallies).forEach(k => { reset[k] = 0; });
    setTallies(reset);
    setLastAction(null);
    toast({ title: 'Tallies Reset', description: 'All vote counts have been reset to zero.' });
  };

  const totalVotes = Object.values(tallies).reduce((a, b) => a + b, 0);

  const handleCertify = () => {
    if (totalVotes === 0) {
      toast({ variant: 'destructive', title: 'No votes', description: 'You must tally at least one vote before certifying.' });
      return;
    }
    if (!confirm('Are you sure you want to certify this election with the current tallies? This action will lock the results.')) return;
    onCertify(tallies);
  };

  // Get key for a candidate
  const getKeyForCandidate = (candidateId) => {
    for (const [key, entry] of Object.entries(keyMap)) {
      if (entry.candidateId === candidateId) return key;
    }
    return null;
  };

  return (
    <div ref={containerRef} className="space-y-4">
      {/* Controls bar */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Button
            variant={isActive ? 'default' : 'outline'}
            size="sm"
            className="gap-2"
            onClick={() => { setIsActive(!isActive); if (!isActive) containerRef.current?.focus(); }}
          >
            <Keyboard className="w-4 h-4" />
            {isActive ? 'Keyboard Active' : 'Enable Keyboard'}
          </Button>
          <Button variant="outline" size="sm" className="gap-1.5" onClick={resetTallies}>
            <RotateCcw className="w-3.5 h-3.5" /> Reset
          </Button>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-sm text-muted-foreground font-medium">
            Total: <span className="text-foreground font-bold">{totalVotes}</span> votes
          </span>
          <Button size="sm" className="gap-1.5" onClick={handleCertify}>
            <CheckCircle2 className="w-4 h-4" /> Certify & Submit
          </Button>
        </div>
      </div>

      {/* Active indicator */}
      {isActive && (
        <div className="bg-primary/10 border border-primary/20 rounded-lg px-4 py-2 flex items-center justify-between">
          <span className="text-sm text-primary font-medium flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-primary animate-pulse" />
            Keyboard tallying active — press assigned keys to count votes
          </span>
          {lastAction && (
            <span className="text-xs text-primary/70">
              Last: <kbd className="px-1.5 py-0.5 bg-primary/20 rounded text-primary font-mono font-bold">{lastAction.key}</kbd> → {lastAction.name}
            </span>
          )}
        </div>
      )}

      {/* Position cards */}
      {positions.map(pos => {
        const posCandidates = candidates.filter(c => c.position_id === pos.id);
        const posTotal = posCandidates.reduce((sum, c) => sum + (tallies[c.id] || 0), 0);

        return (
          <Card key={pos.id}>
            <CardHeader className="pb-2 pt-3 px-4">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-semibold">{pos.title}</CardTitle>
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="text-xs">{pos.seats_available} seat{pos.seats_available > 1 ? 's' : ''}</Badge>
                  <span className="text-xs text-muted-foreground">{posTotal} votes</span>
                </div>
              </div>
            </CardHeader>
            <CardContent className="px-4 pb-3 space-y-2">
              {posCandidates.map(c => {
                const count = tallies[c.id] || 0;
                const pct = posTotal > 0 ? Math.round((count / posTotal) * 100) : 0;
                const assignedKey = getKeyForCandidate(c.id);

                return (
                  <div key={c.id} className="flex items-center gap-3 py-2 px-3 bg-muted/50 rounded-md group hover:bg-muted transition-colors">
                    {/* Key badge */}
                    {assignedKey && (
                      <kbd className={`
                        inline-flex items-center justify-center w-8 h-8 rounded-md border-2 font-mono font-bold text-sm shrink-0 transition-all
                        ${isActive
                          ? 'border-primary bg-primary/10 text-primary shadow-sm'
                          : 'border-border bg-background text-muted-foreground'
                        }
                      `}>
                        {assignedKey}
                      </kbd>
                    )}

                    {/* Name + progress */}
                    <div className="flex-1 min-w-0 space-y-1">
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium truncate">{c.candidate_name}</span>
                        <span className="text-sm font-bold tabular-nums ml-2">
                          {count} <span className="text-xs text-muted-foreground font-normal">({pct}%)</span>
                        </span>
                      </div>
                      <Progress value={pct} className="h-1.5" />
                    </div>

                    {/* Manual +/- buttons */}
                    <div className="flex items-center gap-1 shrink-0">
                      <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => decrementTally(c.id)}>
                        <Minus className="w-3 h-3" />
                      </Button>
                      <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => incrementTally(c.id)}>
                        <Plus className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>
                );
              })}
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}