import { useState } from 'react';
import { type TFunction, Trans } from 'react-i18next';
import { useMutation, useQueryClient } from 'react-query';

import Stack from '@material-hu/mui/Stack';

import Accordion from '@material-hu/components/design-system/Accordion';
import Drawer, {
  type DrawerProps,
} from '@material-hu/components/design-system/Drawer';
import useSnackbar from '@material-hu/components/design-system/Snackbar';
import Title from '@material-hu/components/design-system/Title';

import { pxKeys } from 'src/pages/dashboard/PeopleExperience/queries';
import { updatePartiallySurvey } from 'src/pages/dashboard/PeopleExperience/services';
import { CalcMethod, type TransformedSurvey } from 'src/types/peopleExperience';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { transComponents } from './constants';
import RadioCalcMethod from './RadioCalcMethod';

type CalcMethodDrawer = Pick<DrawerProps, 'open' | 'onClose'> & {
  surveyId: number | null;
  value: TransformedSurvey['calcMethod']['value'];
  disabledAdvancedMethod?: boolean;
};

const CalcMethodDrawer = ({
  open,
  onClose,
  surveyId,
  value: initialValue,
  disabledAdvancedMethod = false,
}: CalcMethodDrawer) => {
  const [value, setValue] = useState<CalcMethod>(initialValue);
  const queryClient = useQueryClient();
  const { enqueueSnackbar } = useSnackbar();

  const { t } = useLokaliseTranslation('people_experience');

  const { mutate: updateCalcMethod, isLoading: isUpdatingCalcMethod } =
    useMutation(updatePartiallySurvey, {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('survey_updated_success'),
          variant: 'success',
        });
        queryClient.invalidateQueries(
          pxKeys.surveyDetail(surveyId ?? undefined),
        );
        onClose?.();
      },
      onError: () => {
        enqueueSnackbar({
          title: t('survey_updated_error'),
          variant: 'error',
        });
      },
    });

  const handleUpdateCalcMethod = () => {
    if (surveyId == null) return;
    updateCalcMethod({
      surveyId,
      topicsCalculationMethod: value,
    });
  };

  const handleClose = () => {
    if (!isUpdatingCalcMethod) {
      onClose?.();
    }
  };

  return (
    <Drawer
      open={open}
      title={t('calculation_format')}
      onClose={handleClose}
      primaryButtonProps={{
        onClick: handleUpdateCalcMethod,
        loading: isUpdatingCalcMethod,
        children: t('save_selection'),
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: handleClose,
        disabled: isUpdatingCalcMethod,
      }}
    >
      <Stack sx={{ gap: 2 }}>
        <Stack
          sx={{
            gap: 2,
            p: 2,
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
          }}
        >
          <Title
            title={t('calc_based_on')}
            variant="S"
          />
          <RadioCalcMethod
            checked={value === CalcMethod.LINEAL}
            onClick={() => setValue(CalcMethod.LINEAL)}
            title={t('classic_method')}
            description={t('linear_average')}
            isMoreUsed
          />
          <RadioCalcMethod
            checked={value === CalcMethod.ADVANCED}
            onClick={() => setValue(CalcMethod.ADVANCED)}
            title={t('advanced_method')}
            disabled={disabledAdvancedMethod}
          />
        </Stack>
        <Stack
          sx={{
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
            p: 2,
            gap: 2,
          }}
        >
          <Title
            title={t('more_info')}
            variant="S"
          />
          <Accordion
            title={t('what_is_classic_method')}
            customDetail={
              <Title
                description={
                  <Trans
                    t={t as TFunction}
                    ns="people_experience"
                    i18nKey="classic_method_definition"
                    components={transComponents}
                  />
                }
              />
            }
            elevation={0}
          />
          <Accordion
            title={t('what_is_advance_method')}
            customDetail={
              <Title
                description={
                  <Trans
                    t={t as TFunction}
                    ns="people_experience"
                    i18nKey="advanced_method_definition"
                    components={transComponents}
                  />
                }
              />
            }
            elevation={0}
          />
        </Stack>
      </Stack>
    </Drawer>
  );
};

export default CalcMethodDrawer;
