import { useState, useEffect, useMemo } from 'react';

/**
 * Custom hook for countdown functionality
 * @param targetDate - The target date/time for the countdown
 * @param updateInterval - How often to update (in milliseconds), defaults to 1000ms
 * @returns Object with countdown string and time remaining in milliseconds
 */
export const useCountdown = (targetDate: Date | string | null, updateInterval: number = 1000) => {
  const [timeRemaining, setTimeRemaining] = useState<number>(0);
  const [isActive, setIsActive] = useState<boolean>(false);

  const targetTime = useMemo(() => {
    if (!targetDate) return null;
    const date = typeof targetDate === 'string' ? new Date(targetDate) : targetDate;
    return isNaN(date.getTime()) ? null : date.getTime();
  }, [targetDate]);

  useEffect(() => {
    if (!targetTime) {
      setTimeRemaining(0);
      setIsActive(false);
      return;
    }

    const updateCountdown = () => {
      const now = Date.now();
      const remaining = targetTime - now;

      if (remaining <= 0) {
        setTimeRemaining(0);
        setIsActive(false);
        return;
      }

      setTimeRemaining(remaining);
      setIsActive(true);
    };

    // Initial update
    updateCountdown();

    // Set up interval only if countdown is still active
    const interval = setInterval(() => {
      updateCountdown();
    }, updateInterval);

    return () => clearInterval(interval);
  }, [targetTime, updateInterval]);

  const countdownString = useMemo(() => {
    if (timeRemaining <= 0) return '';

    const days = Math.floor(timeRemaining / (24 * 60 * 60 * 1000));
    const hours = Math.floor((timeRemaining % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
    const minutes = Math.floor((timeRemaining % (60 * 60 * 1000)) / (60 * 1000));
    const seconds = Math.floor((timeRemaining % (60 * 1000)) / 1000);

    if (days > 0) {
      return `${days}d ${hours}h`;
    } else if (hours > 0) {
      return `${hours}h ${minutes}m`;
    } else if (minutes > 0) {
      return `${minutes}m ${seconds}s`;
    } else {
      return `${seconds}s`;
    }
  }, [timeRemaining]);

  return {
    countdownString,
    timeRemaining,
    isActive,
    targetTime
  };
};

/**
 * Optimized hook for multiple countdowns
 * @param matches - Array of match objects with date and time
 * @param updateInterval - How often to update all countdowns (in milliseconds)
 * @returns Object with countdown strings for each match ID
 */
export const useMultipleCountdowns = (matches: Array<{ id: string | number; date: string; time: string }>, updateInterval: number = 10000) => {
  const [countdowns, setCountdowns] = useState<Record<string, string>>({});

  useEffect(() => {
    if (!matches.length) {
      setCountdowns({});
      return;
    }

    const updateAllCountdowns = () => {
      const now = Date.now();
      const newCountdowns: Record<string, string> = {};

      matches.forEach((match) => {
        const targetTime = new Date(`${match.date}T${match.time || '00:00'}:00`).getTime();

        if (isNaN(targetTime) || targetTime <= now) {
          return; // Skip past matches or invalid dates
        }

        const diff = targetTime - now;
        const days = Math.floor(diff / (24 * 60 * 60 * 1000));
        const hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
        const minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000));

        if (days > 0) {
          newCountdowns[String(match.id)] = `${days}d ${hours}h`;
        } else if (hours > 0) {
          newCountdowns[String(match.id)] = `${hours}h ${minutes}m`;
        } else {
          newCountdowns[String(match.id)] = `${minutes}m`;
        }
      });

      setCountdowns(newCountdowns);
    };

    // Initial update
    updateAllCountdowns();

    // Set up interval
    const interval = setInterval(updateAllCountdowns, updateInterval);

    return () => clearInterval(interval);
  }, [matches, updateInterval]);

  return countdowns;
};
