import React, { useState, useEffect, useCallback } from 'react';
import { useElections } from '@/hooks/useElections';
import { useAssociation } from '@/contexts/AssociationContext';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, Vote, Users, Calendar, Eye, Trash2, Clock, CheckCircle2, Lock, Unlock } from 'lucide-react';
import { format } from 'date-fns';
import ElectionSetupDialog from '@/components/elections/ElectionSetupDialog';
import ElectionDetailDialog from '@/components/elections/ElectionDetailDialog';

const statusConfig = {
  draft: { label: 'Draft', variant: 'secondary', icon: Clock },
  active: { label: 'Active', variant: 'default', icon: Vote },
  closed: { label: 'Closed', variant: 'outline', icon: Lock },
};

export default function ElectionsPage() {
  const associationContext = useAssociation() || {};
  const selectedAssociation = associationContext.selectedAssociation || null;
  const { fetchElections, deleteElection, updateElection, loading } = useElections();
  const [elections, setElections] = useState([]);
  const [statusFilter, setStatusFilter] = useState('all');
  const [setupOpen, setSetupOpen] = useState(false);
  const [detailElection, setDetailElection] = useState(null);

  const loadElections = useCallback(async () => {
    const data = await fetchElections(selectedAssociation?.id || null, statusFilter);
    setElections(data);
  }, [fetchElections, selectedAssociation?.id, statusFilter]);

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

  // Auto-close overdue elections once after load (separate effect to avoid loop)
  useEffect(() => {
    const now = new Date();
    const overdue = elections.filter(el => el.status === 'active' && el.voting_end && new Date(el.voting_end) < now);
    if (overdue.length > 0) {
      Promise.all(overdue.map(el => updateElection(el.id, { status: 'closed' }))).then(() => {
        setElections(prev => prev.map(el => overdue.some(o => o.id === el.id) ? { ...el, status: 'closed' } : el));
      });
    }
  }, [elections.length]); // only re-run when election count changes, not on every render

  const handleDelete = async (id) => {
    if (!confirm('Are you sure you want to delete this election? This cannot be undone.')) return;
    const ok = await deleteElection(id);
    if (ok) loadElections();
  };

  const handleStatusChange = async (id, newStatus) => {
    const ok = await updateElection(id, { status: newStatus });
    if (ok) loadElections();
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Elections</h1>
          <p className="text-muted-foreground mt-1">Manage HOA/Condo elections with secret ballot compliance.</p>
        </div>
        <Button onClick={() => setSetupOpen(true)} className="gap-2">
          <Plus className="w-4 h-4" /> New Election
        </Button>
      </div>

      <div className="flex gap-3 items-center">
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[160px]">
            <SelectValue placeholder="Filter status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Statuses</SelectItem>
            <SelectItem value="draft">Draft</SelectItem>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="closed">Closed</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {loading && !elections.length ? (
        <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>
      ) : elections.length === 0 ? (
        <Card className="border-dashed">
          <CardContent className="py-12 text-center">
            <Vote className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold mb-1">No Elections Found</h3>
            <p className="text-muted-foreground text-sm mb-4">Create your first election to get started.</p>
            <Button onClick={() => setSetupOpen(true)} className="gap-2">
              <Plus className="w-4 h-4" /> Create Election
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {elections.map((election) => {
            const cfg = statusConfig[election.status] || statusConfig.draft;
            const StatusIcon = cfg.icon;
            return (
              <Card key={election.id} className="hover:shadow-md transition-shadow cursor-pointer" onClick={() => setDetailElection(election)}>
                <CardContent className="p-5">
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-3 mb-1">
                        <h3 className="font-semibold text-lg truncate">{election.title}</h3>
                        <Badge variant={cfg.variant} className="gap-1 shrink-0">
                          <StatusIcon className="w-3 h-3" /> {cfg.label}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground mb-2">{election.association?.name}</p>
                      {election.description && (
                        <p className="text-sm text-muted-foreground line-clamp-2">{election.description}</p>
                      )}
                      <div className="flex gap-4 mt-3 text-xs text-muted-foreground">
                        {election.voting_start && (
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {format(new Date(election.voting_start), 'MMM d, yyyy')} — {election.voting_end ? format(new Date(election.voting_end), 'MMM d, yyyy') : 'No end date'}
                          </span>
                        )}
                        <span className="flex items-center gap-1">
                          {election.results_locked ? <Lock className="w-3 h-3" /> : <Unlock className="w-3 h-3" />}
                          Results {election.results_locked ? 'Locked' : 'Unlocked'}
                        </span>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 ml-3" onClick={(e) => e.stopPropagation()}>
                      {election.status === 'draft' && (
                        <Button variant="outline" size="sm" onClick={() => handleStatusChange(election.id, 'active')} className="text-xs">
                          Open Voting
                        </Button>
                      )}
                      {election.status === 'active' && (
                        <Button variant="outline" size="sm" onClick={() => handleStatusChange(election.id, 'closed')} className="text-xs">
                          Close Voting
                        </Button>
                      )}
                      {election.status === 'draft' && (
                        <Button variant="ghost" size="icon" onClick={() => handleDelete(election.id)} className="text-muted-foreground hover:text-destructive h-8 w-8">
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      <ElectionSetupDialog open={setupOpen} onOpenChange={setSetupOpen} onSuccess={loadElections} />
      {detailElection && (
        <ElectionDetailDialog
          open={!!detailElection}
          onOpenChange={(open) => !open && setDetailElection(null)}
          election={detailElection}
          onUpdate={loadElections}
        />
      )}
    </div>
  );
}
