import { useId, useState } from 'react';
import { useMutation, useQueryClient } from 'react-query';

import FormControl from '@material-hu/mui/FormControl';
import RadioGroup from '@material-hu/mui/RadioGroup';
import Skeleton from '@material-hu/mui/Skeleton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import useSnackbarUtils from '@material-hu/components/deprecated/Snackbar';

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

import useSurveyDetail from '../../hooks/useSurveyDetail';
import { pxKeys } from '../../queries';
import CollapsibleSection from '../CollapsibleSection';
import ExoticRadio from '../ExoticRadio';
import Sidebar from '../Sidebar';

import CalcMethodDefinition from './CalcMethodDefinition';

type CalcMethodSidebarProps = {
  open: boolean;
  onClose: () => void;
  surveyId: number | null;
};

const CalcMethodSidebar = ({
  open,
  onClose,
  surveyId,
}: CalcMethodSidebarProps) => {
  const [value, setValue] = useState<CalcMethod>(CalcMethod.LINEAL);
  const radioGroupId = useId();
  const queryClient = useQueryClient();

  const { isLoading: isLoadingSurvey } = useSurveyDetail(
    surveyId ?? undefined,
    {
      onSuccess: (data: Survey) => {
        setValue(data.topicsCalculationMethod);
      },
    },
  );

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

  const { mutate, isLoading: isLoadingMutation } = useMutation(
    updatePartiallySurvey,
    {
      onSuccess: () => {
        showSnackbar(t('SURVEY_UPDATED_SUCCESS'));
        queryClient.invalidateQueries(
          pxKeys.surveyDetail(surveyId ?? undefined),
        );
        onClose();
      },
      onError: () => {
        showSnackbar(t('survey_updated_error'));
      },
    },
  );

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

  const handleChangeCalcMethod = (
    event: React.ChangeEvent<HTMLInputElement>,
  ) => {
    setValue((event.target as HTMLInputElement).value as CalcMethod);
  };

  return (
    <Sidebar
      open={open}
      title={t('CALCULATION_FORMAT')}
      onClose={onClose}
      actionsButtonProps={{
        confirm: {
          title: t('GENERAL:SAVE'),
          onClick: handleUpdateCalcMethod,
          disabled: isLoadingSurvey,
          loading: isLoadingMutation,
        },
        cancel: {
          onClick: onClose,
          disabled: isLoadingSurvey || isLoadingMutation,
        },
      }}
    >
      <Stack sx={{ padding: 3, gap: 2 }}>
        {isLoadingSurvey && (
          <Stack sx={{ gap: 2 }}>
            <Skeleton sx={{ width: '30%' }} />
            <Skeleton
              sx={{ height: '3rem' }}
              variant="rounded"
            />
            <Skeleton
              sx={{ height: '3rem' }}
              variant="rounded"
            />
          </Stack>
        )}
        {!isLoadingSurvey && (
          <FormControl>
            <Typography
              id={radioGroupId}
              component="label"
              variant="subtitle1"
              sx={{
                marginBottom: 2,
              }}
            >
              {t('CALC_BASED_ON')}
            </Typography>
            <RadioGroup
              aria-labelledby={radioGroupId}
              name="calc-format"
              onChange={handleChangeCalcMethod}
              value={value}
              sx={{ gap: 2 }}
            >
              <ExoticRadio
                label={t('CLASSIC_METHOD')}
                value={CalcMethod.LINEAL}
                badge={t('MOST_USED')}
              />
              <ExoticRadio
                label={t('ADVANCED_METHOD')}
                value={CalcMethod.ADVANCED}
              />
            </RadioGroup>
          </FormControl>
        )}
        <Typography variant="subtitle1">{t('MORE_INFO')}</Typography>
        <CollapsibleSection title={t('WHAT_IS_CLASSIC_METHOD')}>
          <CalcMethodDefinition i18nKey="classic_method_definition" />
        </CollapsibleSection>
        <CollapsibleSection title={t('WHAT_IS_ADVANCE_METHOD')}>
          <CalcMethodDefinition i18nKey="advanced_method_definition" />
        </CollapsibleSection>
      </Stack>
    </Sidebar>
  );
};

export default CalcMethodSidebar;
