import useNow from '@/hooks/use-now';
import { Text, Group } from '@mantine/core';
import { useMemo } from 'react';

interface CountdownProps {
  date: Date;
  label?: string;
  color?: string;
}

interface TimeLeft {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
}

function calculateTimeLeft(targetDate: Date, currentTime = new Date()): TimeLeft {
  const difference = targetDate.getTime() - currentTime.getTime();
  
  if (difference <= 0) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0 };
  }

  return {
    days: Math.floor(difference / (1000 * 60 * 60 * 24)),
    hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
    minutes: Math.floor((difference / 1000 / 60) % 60),
    seconds: Math.floor((difference / 1000) % 60)
  };
}

export function Countdown({ date, label, color }: CountdownProps) {
  const now = useNow();
  const timeLeft = useMemo(() => calculateTimeLeft(date, now), [date, now]);

  const formatTime = () => {
    const pad = (num: number) => num.toString().padStart(2, '0');
    
    if (timeLeft.days > 0) {
      return `${timeLeft.days}d ${pad(timeLeft.hours)}:${pad(timeLeft.minutes)}:${pad(timeLeft.seconds)}`;
    } else {
      return `${pad(timeLeft.hours)}:${pad(timeLeft.minutes)}:${pad(timeLeft.seconds)}`;
    }
  };

  return (
    <Group gap="xs">
      {label && <Text size='sm' fw={500}>{label}:</Text>}
      <Text size='sm' fw={600} c={color} ff="monospace">
        {formatTime()}
      </Text>
    </Group>
  );
}

export default Countdown;