import { useMemo } from 'react';

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

import Breakdown from '@material-hu/components/composed-components/Breakdown';
import MidCircle from '@material-hu/components/composed-components/MidCircle';
import Pie from '@material-hu/components/composed-components/Pie';

import { useLokaliseTranslation } from 'src/utils/i18n';

import useGetSessionsStats from '../../hooks/useGetSessionsStats';

import StatCard from './StatCard';

const SessionsStats = () => {
  const { palette } = useTheme();
  const { t } = useLokaliseTranslation('learning');

  const { data: stats, isLoading } = useGetSessionsStats();

  const hideStats =
    !stats?.draftCount && !stats?.publishedCount && !stats?.finishedCount;

  const attendancePercentage = useMemo(() => {
    if (!stats?.totalUserFinishedSessionsCount) return 0;

    return (
      ((stats?.userAssistedCount ?? 0) /
        stats?.totalUserFinishedSessionsCount) *
      100
    );
  }, [stats?.userAssistedCount, stats?.totalUserFinishedSessionsCount]);

  if (hideStats) return null;

  const typeItems = [
    {
      value: stats?.virtualCount ?? 0,
      label: t('session.type.virtual_one'),
      color: palette.graphics?.primaryGraphic,
    },
    {
      value: stats?.presentialCount ?? 0,
      label: t('session.type.presential_one'),
      color: palette.border?.primaryBorder,
    },
  ];

  const statusItems = [
    {
      value: stats?.draftCount ?? 0,
      label: t('session.status.draft'),
      color: palette.textColors?.neutralTextLighter,
    },
    {
      value: stats?.publishedCount ?? 0,
      label: t('session.status.published_other'),
      color: palette.textColors?.successText,
    },
    {
      value: stats?.finishedCount ?? 0,
      label: t('session.status.finished_other'),
      color: palette.textColors?.secondaryText,
    },
  ];

  return (
    <Stack
      sx={{
        display: 'grid',
        gap: 3,
        gridTemplateColumns: {
          xs: '1fr',
          lg: 'repeat(3, 1fr)',
        },
      }}
    >
      <StatCard
        title={t('session.attendance.title')}
        description={t('session.attendance.description')}
      >
        <MidCircle
          current={attendancePercentage}
          loading={isLoading}
          sx={{ '& .MidCircleChart-root': { maxWidth: '200px' }, my: 'auto' }}
        />
      </StatCard>
      <StatCard title={t('session.type.title_other')}>
        <Pie
          items={typeItems}
          loading={isLoading}
          legend="bottom"
        />
      </StatCard>
      <StatCard title={t('general:state')}>
        <Breakdown
          sx={{ my: 'auto' }}
          items={statusItems}
          loading={isLoading}
        />
      </StatCard>
    </Stack>
  );
};

export default SessionsStats;
