import { FC, forwardRef, Fragment } from 'react';

import {
  IconCalendar,
  IconChartLine,
  IconClock,
  IconEye,
  IconInfoCircle,
  IconHourglassEmpty,
  IconTrendingUp,
  TablerIcon,
  IconUser,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Grid from '@material-hu/mui/Grid';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuSkeleton from '@material-hu/components/design-system/Skeleton';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { useAuth } from 'src/contexts/JWTContext';
import { LiveStreamStats } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  formatDurationLivestream,
  formatStartedAtLivestream,
  formatStartTimetLivestream,
} from './utils';

type SummaryProps = {
  summary: Partial<Omit<LiveStreamStats, 'viewers' | 'id'>>;
  currentLocale: Locale;
  isLoadingStats: boolean;
};

const Summary = forwardRef<HTMLDivElement, SummaryProps>(function Summary(
  { summary, currentLocale, isLoadingStats },
  ref,
) {
  const { t } = useLokaliseTranslation('livestream');
  const {
    averageViewingTimeSeconds,
    endedAt,
    maximumConcurrentViewers,
    startedAt,
    totalViewers,
    totalUniqueViewers,
  } = summary;
  const { instance } = useAuth();

  const formattedStartedAt = formatStartedAtLivestream(
    startedAt,
    currentLocale,
  );

  const formattedStartTime = formatStartTimetLivestream(
    startedAt,
    instance?.timezone,
  );

  const formattedDuration = formatDurationLivestream(
    startedAt,
    endedAt,
    currentLocale,
  );

  const formattedAvgRetention = formatDurationLivestream(
    0,
    averageViewingTimeSeconds,
    currentLocale,
  );

  const SUMMARY_ITEMS: SummaryItemProps[] = [
    {
      Icon: IconCalendar,
      iconColor: 'default',
      label: t('TRANSMISSION_DATE'),
      value: formattedStartedAt,
    },
    {
      Icon: IconClock,
      iconColor: 'default',
      label: t('START_TIME'),
      value: formattedStartTime,
    },
    {
      Icon: IconHourglassEmpty,
      iconColor: 'default',
      label: t('TRANSMISSION_DURATION'),
      value: formattedDuration,
    },
    {
      Icon: IconUser,
      iconColor: 'highlight',
      label: t('USERS_CONNECTED'),
      value: totalUniqueViewers || 0,
      info: t('USERS_CONNECTED_INFO'),
    },
    {
      Icon: IconEye,
      iconColor: 'highlight',
      label: t('VIEW_BY'),
      value: totalViewers || 0,
      info: t('VIEW_BY_INFO'),
    },
    {
      Icon: IconTrendingUp,
      iconColor: 'highlight',
      label: t('MAX_AUDIENCE'),
      value: maximumConcurrentViewers || 0,
      info: t('MAX_AUDIENCE_INFO'),
    },
    {
      Icon: IconChartLine,
      iconColor: 'highlight',
      label: t('AVG_RETENTION'),
      value: formattedAvgRetention,
      info: t('AVG_RETENTION_INFO'),
    },
  ];

  return (
    <Stack ref={ref}>
      <HuCardContainer
        sx={{ p: 1 }}
        fullWidth
      >
        <Grid
          container
          rowSpacing={3}
        >
          {SUMMARY_ITEMS.map((item, index) => (
            <Fragment key={item.label}>
              {index === 3 && (
                <Grid
                  item
                  xs={12}
                >
                  <Divider />
                </Grid>
              )}
              <Grid
                item
                xs={12}
                md={index < 3 ? 4 : 3}
              >
                <SummaryItem
                  {...item}
                  isLoading={isLoadingStats}
                />
              </Grid>
            </Fragment>
          ))}
        </Grid>
      </HuCardContainer>
    </Stack>
  );
});

type SummaryItemProps = {
  Icon: TablerIcon;
  iconColor: 'default' | 'highlight' | 'primary';
  label: string;
  value: string | number;
  isLoading?: boolean;
  info?: string;
};

const SummaryItem: FC<SummaryItemProps> = ({
  Icon,
  iconColor,
  label,
  value,
  info,
  isLoading,
}) => {
  const theme = useTheme();

  return (
    <Stack sx={{ gap: 1 }}>
      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
        <HuAvatar
          Icon={Icon}
          color={iconColor}
        />
        <Typography
          variant="globalS"
          color={theme => theme.palette.new.text.neutral.lighter}
        >
          {label}
        </Typography>
        {info && (
          <HuTooltip description={info}>
            <IconInfoCircle
              size={16}
              color={theme.palette.new.text.neutral.lighter}
            />
          </HuTooltip>
        )}
      </Stack>
      <HuSkeleton
        variant="text"
        width={250}
        isLoading={isLoading}
      >
        <Typography
          variant="globalL"
          fontWeight="fontWeightSemiBold"
          sx={{ ml: 0.5 }}
        >
          {value}
        </Typography>
      </HuSkeleton>
    </Stack>
  );
};

export default Summary;
