import React, { useState } from 'react';
import { ref, set, get } from 'firebase/database';
import { realtimeDb } from '../../services/firebase';
import VoteCard from '../VoteCard/VoteCard';
import styles from './VotingBoard.module.css';

const fibonacciNumbers = [0, 1, 2, 3, 5, 8, 13, 21, 9999];

const VotingBoard = ({ sessionId, userId }) => {
  const [selectedVote, setSelectedVote] = useState(null);

  const handleVote = async (number) => {
    setSelectedVote(number);

    const userVoteRef = ref(
      realtimeDb,
      `sessions/${sessionId}/votes/${userId}`
    );

    // Get the current vote for this user (if any)
    const snapshot = await get(userVoteRef);
    const existingVote =
      snapshot.exists() && snapshot.val() > -1 ? snapshot.val() : null;

    // Set the new vote for the user
    await set(userVoteRef, number);

    const sessionRef = ref(realtimeDb, `sessions/${sessionId}`);
    const sessionSnapshot = await get(sessionRef);

    if (sessionSnapshot.exists()) {
      const sessionData = sessionSnapshot.val() || {};

      // Increment votedUsers only if the user hasn't voted before
      if (existingVote === null) {
        const votedUsers = sessionData.votedUsers || 0;
        await set(sessionRef, {
          ...sessionData,
          votedUsers: votedUsers + 1,
        });
      }
    } else {
      console.error("Session doesn't exist");
    }
  };

  return (
    <div className={styles.votingBoard}>
      <h2>Select Your Vote</h2>
      <div className={styles.voteCards}>
        {fibonacciNumbers.map((num) => (
          <VoteCard
            key={num}
            className={styles.voteCard}
            number={num}
            onClick={() => handleVote(num)}
            isSelected={selectedVote === num}
          />
        ))}
      </div>
    </div>
  );
};

export default VotingBoard;
