import { type FC } from 'react';

import { IconAlertTriangle } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';
import useMediaQuery from '@material-hu/mui/useMediaQuery';

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTitle from '@material-hu/components/design-system/Title';

import { formatSecondsToTime } from 'src/pages/dashboard/serviceManagement/utils';
import { type ServiceMetrics as ServiceMetricsType } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ServiceItemStateChart from '../../../general/charts/ServiceItemStateChart';
import ServiceItemsStateChartSkeleton from '../../../general/charts/ServiceItemStateChartSkeleton';

import ServiceMetricsSkeleton from './ServiceMetricsSkeleton';

type Props = {
  serviceMetrics?: ServiceMetricsType;
  serviceMetricsChartData: [string[], number[]] | [null, null];
  helpDeskName?: string;
  hasCsat: boolean;
  isLoading: boolean;
  isError: boolean;
  onRetry: () => void;
};

const ServiceMetrics: FC<Props> = ({
  serviceMetrics,
  serviceMetricsChartData,
  helpDeskName,
  hasCsat,
  isLoading,
  isError,
  onRetry,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const theme = useTheme();
  const isLessThanLgScreenSize = useMediaQuery(theme.breakpoints.down('lg'));
  const titleVariant = isLessThanLgScreenSize ? 'L' : 'XL';

  if (isLoading) {
    return (
      <HuCardContainer fullWidth>
        <Stack sx={{ gap: 2 }}>
          <HuTitle
            title={t('service_metrics')}
            variant="M"
          />
          <ServiceMetricsSkeleton />
          <Stack
            sx={{
              p: 2,
              borderRadius: 2,
              width: 1,
              height: '300px',
              backgroundColor: ({ palette }) =>
                palette.new.background.layout.default,
            }}
          >
            <Typography
              variant="globalS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.lighter,
              }}
            >
              {t('tasks_by_state_amount')}
            </Typography>
            <ServiceItemsStateChartSkeleton />
          </Stack>
        </Stack>
      </HuCardContainer>
    );
  }

  if (isError) {
    return (
      <HuStateCard
        variant="S"
        color="error"
        Icon={IconAlertTriangle}
        title={t('error_cant_show_service_metrics')}
        description={t('try_again_later')}
        action={{
          children: t('try_again'),
          onClick: onRetry,
        }}
        sx={{
          py: 6,
        }}
      />
    );
  }

  return (
    <HuCardContainer fullWidth>
      <Stack sx={{ gap: 2 }}>
        <HuTitle
          title={t('service_metrics')}
          variant="M"
        />
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 2,
            flexWrap: 'wrap',
          }}
        >
          <HuTitle
            copetin={t('total_tasks')}
            copetinTooltip={t('total_tasks_tooltip', {
              name: helpDeskName,
            })}
            title={Intl.NumberFormat().format(serviceMetrics?.totalTasks ?? 0)}
            variant={titleVariant}
            sx={{ flex: 1 }}
          />
          <Divider
            orientation="vertical"
            flexItem
          />
          <HuTitle
            copetin={t('average_assignment_time')}
            copetinTooltip={t('average_assignment_time_tooltip', {
              name: helpDeskName,
            })}
            title={formatSecondsToTime(
              serviceMetrics?.avgAssignmentTimeSeconds ?? 0,
            )}
            variant={titleVariant}
            sx={{ flex: 1 }}
          />
          <Divider
            orientation="vertical"
            flexItem
          />
          <HuTitle
            copetin={t('average_resolution_time')}
            copetinTooltip={t('average_resolution_time_tooltip', {
              name: helpDeskName,
            })}
            title={formatSecondsToTime(
              serviceMetrics?.avgResolutionTimeSeconds ?? 0,
            )}
            variant={titleVariant}
            sx={{ flex: 1 }}
          />
          {hasCsat && (
            <>
              <Divider
                orientation="vertical"
                flexItem
              />
              <HuTitle
                copetin={t('average_csat_rating')}
                copetinTooltip={t('average_csat_rating_tooltip', {
                  name: helpDeskName,
                })}
                title={serviceMetrics?.avgCsatRating?.toFixed(2) ?? '-'}
                variant={titleVariant}
                sx={{ flex: 1 }}
              />
            </>
          )}
        </Stack>
        <Stack
          sx={{
            p: 2,
            borderRadius: 2,
            width: 1,
            height: '300px',
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.default,
          }}
        >
          <Typography
            variant="globalS"
            sx={{
              color: ({ palette }) => palette.new.text.neutral.lighter,
            }}
          >
            {t('tasks_by_state_amount')}
          </Typography>
          <ServiceItemStateChart
            data={serviceMetricsChartData[1] ?? []}
            labels={serviceMetricsChartData[0] ?? []}
            loading={isLoading}
          />
        </Stack>
      </Stack>
    </HuCardContainer>
  );
};

export default ServiceMetrics;
