import { useEffect, useState } from 'react';

import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { useTranslation } from '../i18n';

type NextEventCounterProps = {
  title: string;
  date: string;
};

type TimeLeft = {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
};

const getTimeLeft = (date: string): TimeLeft | null => {
  const diff = new Date(date).getTime() - Date.now();
  if (diff <= 0) return null;

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

const pad = (n: number) => String(n).padStart(2, '0');

const NextEventCounter = ({ title, date }: NextEventCounterProps) => {
  const { t } = useTranslation();
  const theme = useTheme();
  const [timeLeft, setTimeLeft] = useState<TimeLeft | null>(() =>
    getTimeLeft(date),
  );

  useEffect(() => {
    const id = setInterval(() => {
      const next = getTimeLeft(date);
      if (!next) {
        clearInterval(id);
      }
      setTimeLeft(next);
    }, 1000);

    return () => clearInterval(id);
  }, [date]);

  if (!timeLeft) return null;

  const brand500 = theme.palette.newBase?.brand[500];
  const brand800 = theme.palette.newBase?.brand[800];

  const units = [
    { label: t('days'), value: timeLeft.days },
    { label: t('hours'), value: timeLeft.hours },
    { label: t('minutes'), value: timeLeft.minutes },
    { label: t('seconds'), value: timeLeft.seconds },
  ];

  return (
    <Stack
      sx={{
        background: `linear-gradient(to right, ${brand800}, ${brand500})`,
        borderRadius: theme.shape.borderRadiusL,
        padding: { xs: 2, md: 3 },
        gap: 1.5,
        flexDirection: { xs: 'column', md: 'row' },
        alignItems: 'center',
      }}
    >
      <Typography
        variant="globalXL"
        fontWeight="fontWeightSemiBold"
        sx={{
          color: theme => theme.palette.new.text.neutral.inverted,
          width: '100%',
          textAlign: 'left',
        }}
      >
        {title}
      </Typography>
      <Stack
        sx={{
          flexDirection: 'row',
          gap: 1,
          justifyContent: {
            xs: 'space-between',
            md: 'flex-end',
          },
          width: '100%',
        }}
      >
        {units.map(unit => (
          <Stack
            key={unit.label}
            sx={{
              flex: 1,
              maxWidth: {
                xs: '100%',
                md: 80,
              },
              height: 56,
              alignItems: 'center',
              justifyContent: 'center',
              gap: 0.5,
              borderRadius: theme.shape.borderRadiusM,
              backgroundColor: 'rgba(255, 255, 255, 0.23)',
              border: '1px solid rgba(255, 255, 255, 0.15)',
            }}
          >
            <Typography
              variant="globalXXS"
              sx={{
                color: theme => theme.palette.new.text.neutral.inverted,
                lineHeight: 1,
              }}
            >
              {unit.label}
            </Typography>
            <Typography
              variant="globalL"
              fontWeight="fontWeightSemiBold"
              sx={{
                color: theme => theme.palette.new.text.neutral.inverted,
                lineHeight: 1,
              }}
            >
              {pad(unit.value)}
            </Typography>
          </Stack>
        ))}
      </Stack>
    </Stack>
  );
};

export default NextEventCounter;
