'use client';

import { useEffect, useState } from 'react';

import { VOTE_CLOSES_BEFORE_END } from './constants';
import { SongData } from './interfaces';

// Helper function to format countdown time
const formatCountdown = (minutes: number, seconds: number): string => {
  if (minutes === 0) {
    return `${seconds}s`;
  }
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};

interface VoteCountdownProps {
  currentSong: SongData | null;
  voteClosed: boolean;
}

const VoteCountdown = ({ currentSong, voteClosed }: VoteCountdownProps) => {
  const [timeUntilNextVote, setTimeUntilNextVote] = useState<string | null>(
    null
  );

  useEffect(() => {
    if (!currentSong) {
      setTimeUntilNextVote(null);
      return;
    }

    const updateCountdown = () => {
      const now = new Date().getTime();
      const songStartTime = new Date(currentSong.start_time).getTime();
      const songEndTime = songStartTime + currentSong.duration * 1000;
      const voteCloseTime = songEndTime - VOTE_CLOSES_BEFORE_END * 1000;
      const timeLeft = voteCloseTime - now;

      if (timeLeft <= 0) {
        // Voting is closed, show countdown to next vote (when song ends)
        const timeUntilSongEnd = songEndTime - now;

        if (timeUntilSongEnd > 0) {
          const minutes = Math.floor(timeUntilSongEnd / 60000);
          const seconds = Math.floor((timeUntilSongEnd % 60000) / 1000);
          setTimeUntilNextVote(
            `Voting is closed. Next vote starts in ${formatCountdown(minutes, seconds)}`
          );
        } else if (voteClosed) {
          setTimeUntilNextVote('Voting is closed. Next vote will start soon!');
        } else {
          setTimeUntilNextVote('Voting is open!');
        }
        return;
      }

      const minutes = Math.floor(timeLeft / 60000);
      const seconds = Math.floor((timeLeft % 60000) / 1000);
      setTimeUntilNextVote(
        `Vote closes in ${formatCountdown(minutes, seconds)}`
      );
    };

    updateCountdown();
    const interval = setInterval(updateCountdown, 1000);
    return () => clearInterval(interval);
  }, [currentSong, voteClosed]);

  return (
    <div className='mt-1 text-left text-[10px] font-medium text-white/60 md:mt-2 md:text-xs'>
      {timeUntilNextVote || 'Loading vote timer...'}
    </div>
  );
};

export default VoteCountdown;
