import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';

export function useVotes() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { toast } = useToast();
  const { user } = useAuth();

  const fetchBoardVotes = useCallback(async (associationId, status = null) => {
    setLoading(true);
    setError(null);
    try {
      let query = supabase
        .from('board_votes')
        .select(`
          *,
          client:association_id(id, name)
        `)
        .order('created_at', { ascending: false });

      if (associationId) {
        query = query.eq('association_id', associationId);
      }
      
      if (status && status !== 'all') {
        query = query.eq('status', status);
      }

      const { data, error: fetchError } = await query;

      if (fetchError) throw fetchError;
      return data;
    } catch (err) {
      console.error('Error fetching votes:', err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchVoteResponses = useCallback(async (boardVoteId) => {
    try {
      const { data, error: fetchError } = await supabase
        .from('board_vote_responses')
        .select(`
            *,
            user:user_id(id, full_name, first_name, last_name, email)
        `)
        .eq('board_vote_id', boardVoteId);

      if (fetchError) throw fetchError;
      return data;
    } catch (err) {
      console.error('Error fetching vote responses:', err);
      return [];
    }
  }, []);

  const createBoardVote = async (voteData) => {
    setLoading(true);
    try {
      const { error: insertError } = await supabase
        .from('board_votes')
        .insert({
          ...voteData,
          created_by: user.id
        });

      if (insertError) throw insertError;
      
      toast({
        title: "Success",
        description: "Board vote created successfully."
      });
      return true;
    } catch (err) {
      console.error('Error creating vote:', err);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to create board vote."
      });
      return false;
    } finally {
      setLoading(false);
    }
  };

  const recordVote = async (boardVoteId, userId, voteOption) => {
    setLoading(true);
    try {
      const { error: insertError } = await supabase
        .from('board_vote_responses')
        .insert({
          board_vote_id: boardVoteId,
          user_id: userId,
          vote_option: voteOption,
          recorded_by: user.id
        });

      if (insertError) throw insertError;
      
      toast({ title: "Vote Recorded", description: "The vote has been successfully recorded." });
      return true;
    } catch (err) {
      console.error('Error recording vote:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
      return false;
    } finally {
      setLoading(false);
    }
  };

  const castVote = async (boardVoteId, voteOption) => {
    setLoading(true);
    try {
        const { data: existing } = await supabase
            .from('board_vote_responses')
            .select('id')
            .eq('board_vote_id', boardVoteId)
            .eq('user_id', user.id)
            .single();
            
        if (existing) {
            throw new Error("You have already voted on this item.");
        }

        const { error: insertError } = await supabase
            .from('board_vote_responses')
            .insert({
            board_vote_id: boardVoteId,
            user_id: user.id,
            vote_option: voteOption
            });

        if (insertError) throw insertError;
        
        toast({ title: "Vote Submitted", description: "Your vote has been cast." });
        return true;
    } catch (err) {
        console.error('Error casting vote:', err);
        toast({ variant: "destructive", title: "Error", description: err.message });
        return false;
    } finally {
        setLoading(false);
    }
  };

  const closeVote = async (boardVoteId) => {
    setLoading(true);
    try {
      const { error: updateError } = await supabase
        .from('board_votes')
        .update({ status: 'closed' })
        .eq('id', boardVoteId);

      if (updateError) throw updateError;
      
      toast({ title: "Vote Closed", description: "Voting is now closed for this item." });
      return true;
    } catch (err) {
      console.error('Error closing vote:', err);
      toast({ variant: "destructive", title: "Error", description: "Failed to close vote." });
      return false;
    } finally {
      setLoading(false);
    }
  };
  
  const calculateVoteResults = (responses, options) => {
      const total = responses.length;
      const results = {};
      
      if (options && Array.isArray(options)) {
          options.forEach(opt => {
              results[opt] = { count: 0, percentage: 0 };
          });
      }

      responses.forEach(r => {
          if (results[r.vote_option]) {
              results[r.vote_option].count++;
          } else {
              if (!results[r.vote_option]) {
                 results[r.vote_option] = { count: 0, percentage: 0 };
              }
              results[r.vote_option].count++;
          }
      });

      Object.keys(results).forEach(key => {
          results[key].percentage = total > 0 
            ? Math.round((results[key].count / total) * 100) 
            : 0;
      });

      return { total, results };
  };

  return {
    loading,
    error,
    fetchBoardVotes,
    fetchVoteResponses,
    createBoardVote,
    recordVote,
    castVote,
    closeVote,
    calculateVoteResults
  };
}
