import { memo, useMemo } from 'react';

import { isNil } from 'lodash-es';
import InfoOutlinedIcon from '@material-hu/icons/material/InfoOutlined';
import {
  IconFileExport,
  IconNumbers,
  IconUsers,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import { type LeaderStatCardsProps } from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  formatPercentage,
  formatRatio,
  formatScoreToDisplay,
} from '../../../utils';

import LeaderStatCardsSkeleton from './LeaderStatCardsSkeleton';

const LeaderStatCards = ({ stats, isLoading }: LeaderStatCardsProps) => {
  const { t } = useLokaliseTranslation('performance');

  const cards = useMemo(() => {
    if (isNil(stats)) return [];

    const {
      teamScore,
      evaluatedCollaborators,
      totalCollaborators,
      deliveredEvaluations,
    } = stats;
    const evaluatedReady =
      !isNil(evaluatedCollaborators) &&
      !isNil(totalCollaborators) &&
      totalCollaborators > 0;
    const deliveredDenominator =
      !isNil(evaluatedCollaborators) && evaluatedCollaborators > 0
        ? evaluatedCollaborators
        : totalCollaborators;
    const deliveredReady =
      !isNil(deliveredEvaluations) &&
      !isNil(deliveredDenominator) &&
      deliveredDenominator > 0;

    return [
      {
        id: 'team_score',
        Icon: IconNumbers,
        label: t('manage_team.team_general_score'),
        tooltip: t('manage_team.team_general_score_tooltip'),
        ariaLabel: t('manage_team.team_general_score_tooltip'),
        primary: !isNil(teamScore) ? formatScoreToDisplay(teamScore) : '—',
        secondary: undefined,
      },
      {
        id: 'evaluated',
        Icon: IconUsers,
        label: t('manage_team.evaluated_collaborators'),
        tooltip: t('manage_team.evaluated_collaborators_tooltip'),
        ariaLabel: t('manage_team.evaluated_collaborators_tooltip'),
        primary: evaluatedReady
          ? formatPercentage(evaluatedCollaborators, totalCollaborators)
          : '—',
        secondary: evaluatedReady
          ? formatRatio(evaluatedCollaborators, totalCollaborators)
          : undefined,
      },
      {
        id: 'delivered',
        Icon: IconFileExport,
        label: t('manage_team.delivered_evaluations'),
        tooltip: t('manage_team.delivered_evaluations_tooltip'),
        ariaLabel: t('manage_team.delivered_evaluations_tooltip'),
        primary: deliveredReady
          ? formatPercentage(deliveredEvaluations, deliveredDenominator)
          : '—',
        secondary: deliveredReady
          ? formatRatio(deliveredEvaluations, deliveredDenominator)
          : undefined,
      },
    ];
  }, [t, stats]);

  if (isLoading || isNil(stats)) {
    return <LeaderStatCardsSkeleton />;
  }

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        gap: 2,
        flexWrap: 'wrap',
      }}
    >
      {cards.map(
        ({ id, Icon, label, tooltip, ariaLabel, primary, secondary }) => (
          <HuCardContainer
            key={id}
            sx={{ flex: '1 1 240px' }}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'flex-start',
                gap: 2,
              }}
            >
              <Stack
                sx={{
                  width: 40,
                  height: 40,
                  borderRadius: 1.5,
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexShrink: 0,
                  backgroundColor: theme =>
                    theme.palette.newBase?.brand[50] ??
                    theme.palette.primary.light,
                  color: theme =>
                    theme.palette.newBase?.brand[900] ??
                    theme.palette.primary.main,
                }}
              >
                <Icon
                  size={20}
                  stroke={1.5}
                />
              </Stack>
              <Stack sx={{ flex: 1, gap: 0.5, minWidth: 0 }}>
                <Stack
                  sx={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    gap: 2,
                  }}
                >
                  <Typography variant="body2">{label}</Typography>
                  <HuTooltip description={tooltip}>
                    <InfoOutlinedIcon
                      aria-label={ariaLabel}
                      sx={{ cursor: 'help', fontSize: 16 }}
                    />
                  </HuTooltip>
                </Stack>
                <Stack
                  sx={{
                    flexDirection: 'row',
                    alignItems: 'baseline',
                    gap: 2,
                    flexWrap: 'wrap',
                  }}
                >
                  <Typography
                    variant="h4"
                    sx={{ fontWeight: 600 }}
                  >
                    {primary}
                  </Typography>
                  {secondary && (
                    <Typography
                      variant="body1"
                      sx={{ color: 'text.secondary' }}
                    >
                      {secondary}
                    </Typography>
                  )}
                </Stack>
              </Stack>
            </Stack>
          </HuCardContainer>
        ),
      )}
    </Stack>
  );
};

export default memo(LeaderStatCards);
