import React, { useState, useEffect, useCallback } from 'react';
import { useElections } from '@/hooks/useElections';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Vote, Calendar, Clock, CheckCircle2, Lock } from 'lucide-react';
import { format } from 'date-fns';
import ElectionVotingPage from '@/components/elections/ElectionVotingPage';

export default function HomeownerElectionsPage() {
  const { fetchElections } = useElections();
  const { user } = useAuth();
  const [elections, setElections] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedElection, setSelectedElection] = useState(null);
  const [voterStatuses, setVoterStatuses] = useState({});

  const loadElections = useCallback(async () => {
    setLoading(true);
    try {
      // Get user's association IDs via owners table
      const { data: owners } = await supabase
        .from('owners')
        .select('association_id, id')
        .eq('user_id', user?.id)
        .neq('status', 'archived');

      if (!owners?.length) { setElections([]); return; }

      const assocIds = [...new Set(owners.map(o => o.association_id))];
      const ownerIds = owners.map(o => o.id);

      const { data: electionData } = await supabase
        .from('elections')
        .select('*, association:association_id(id, name)')
        .in('association_id', assocIds)
        .in('status', ['active', 'closed'])
        .order('created_at', { ascending: false });

      setElections(electionData || []);

      // Check voter status for each election
      if (electionData?.length) {
        const { data: voterRecords } = await supabase
          .from('election_eligible_voters')
          .select('election_id, has_voted, has_consent')
          .in('election_id', electionData.map(e => e.id))
          .in('owner_id', ownerIds);

        const statuses = {};
        (voterRecords || []).forEach(v => {
          statuses[v.election_id] = v;
        });
        setVoterStatuses(statuses);
      }
    } finally {
      setLoading(false);
    }
  }, [user?.id]);

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

  if (selectedElection) {
    return (
      <div className="space-y-4">
        <Button variant="ghost" onClick={() => setSelectedElection(null)} className="text-sm">← Back to Elections</Button>
        <ElectionVotingPage electionId={selectedElection.id} />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Elections</h1>
        <p className="text-muted-foreground mt-1">View and participate in community elections.</p>
      </div>

      {loading ? (
        <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</h3>
            <p className="text-muted-foreground text-sm">There are no active elections at this time.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {elections.map(election => {
            const voter = voterStatuses[election.id];
            const isOpen = election.status === 'active' && (!election.voting_end || new Date(election.voting_end) > new Date());
            return (
              <Card key={election.id} className="hover:shadow-md transition-shadow">
                <CardContent className="p-5">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-1">
                        <h3 className="font-semibold text-lg">{election.title}</h3>
                        <Badge variant={isOpen ? 'default' : 'secondary'}>
                          {isOpen ? 'Open' : election.status === 'closed' ? 'Closed' : 'Upcoming'}
                        </Badge>
                        {voter?.has_voted && (
                          <Badge variant="outline" className="gap-1 text-primary border-primary">
                            <CheckCircle2 className="w-3 h-3" /> Voted
                          </Badge>
                        )}
                      </div>
                      <p className="text-sm text-muted-foreground">{election.association?.name}</p>
                      {election.description && <p className="text-sm text-muted-foreground mt-1">{election.description}</p>}
                      {election.voting_end && (
                        <p className="text-xs text-muted-foreground mt-2 flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {isOpen ? 'Closes' : 'Closed'}: {format(new Date(election.voting_end), 'MMM d, yyyy h:mm a')}
                        </p>
                      )}
                    </div>
                    <div className="ml-3">
                      {isOpen && voter && voter.has_consent ? (
                        <Button onClick={() => setSelectedElection(election)} className="gap-2">
                          <Vote className="w-4 h-4" /> {voter.has_voted ? 'Change Vote' : 'Vote Now'}
                        </Button>
                      ) : isOpen && voter && !voter.has_consent ? (
                        <Badge variant="outline" className="text-amber-600 border-amber-300">Consent Required</Badge>
                      ) : (
                        <Lock className="w-5 h-5 text-muted-foreground" />
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
