import { type FC } from 'react';
import { FormProvider, useForm, useWatch } from 'react-hook-form';

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

import HuDialog from '@material-hu/components/design-system/Dialog';
import HuRadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';

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

type TimerModalProps = {
  title: string;
  description: string;
  options: { label: string; value: string }[];
  onClose: () => void;
  onSubmit: (option: string) => void;
  isLoading: boolean;
  primaryButtonLabel: string;
  defaultOption?: string;
};

const TimerModal: FC<TimerModalProps> = props => {
  const {
    title,
    description,
    options,
    onClose,
    onSubmit,
    isLoading,
    primaryButtonLabel,
    defaultOption = '',
  } = props;
  const { t } = useLokaliseTranslation();

  const form = useForm({
    defaultValues: {
      option: defaultOption,
    },
  });
  const option = useWatch({ control: form.control, name: 'option' });

  const handleCLose = () => {
    form.reset();
    onClose();
  };

  const handleSubmitOption = () => {
    onSubmit(option);
    handleCLose();
  };

  const handleChange = (option: string) => {
    form.setValue('option', option);
  };

  return (
    <HuDialog
      title={title}
      primaryButtonProps={{
        children: primaryButtonLabel,
        disabled: !option,
        onClick: handleSubmitOption,
        loading: isLoading,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: handleCLose,
      }}
      body={
        <FormProvider {...form}>
          <form style={{ width: '100%' }}>
            <Typography variant="globalS">{description}</Typography>
            <Stack sx={{ mt: 3, gap: 1 }}>
              {options.map(opt => (
                <HuRadioButton
                  stackSx={{ width: 'fit-content' }}
                  key={opt.value}
                  label={opt.label}
                  value={opt.value}
                  onClick={() => handleChange(opt.value)}
                  isActive={option === opt.value}
                />
              ))}
            </Stack>
          </form>
        </FormProvider>
      }
      onClose={handleCLose}
    />
  );
};

export default TimerModal;
