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

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

import AcceptCancelDialog, {
  AcceptCancelDialogProps,
} from 'src/components/AcceptCancelDialog';
import FormTextField from 'src/components/FormInputs/FormTextField';

export type FormConfirmationDialogWithReasonProps = AcceptCancelDialogProps & {
  onClose?: () => void;
  placeholder: string;
  submit: (values: any) => void;
  description?: string;
  acceptDisabled?: boolean;
};

const FormConfirmationDialogWithReason: FC<
  FormConfirmationDialogWithReasonProps
> = props => {
  const {
    description,
    placeholder,
    submit,
    onClose,
    acceptDisabled = false,
    ...dialogProps
  } = props;

  const form = useForm({
    defaultValues: {
      message: '',
    },
  });

  const { setValue, watch, handleSubmit } = form;

  const handleClose = () => {
    onClose?.();
    setValue('message', '');
  };

  return (
    <AcceptCancelDialog
      {...dialogProps}
      onCancel={handleClose}
      onAccept={handleSubmit(submit)}
      disabled={acceptDisabled && !watch().message}
      fullWidth
      maxWidth="sm"
    >
      <Box
        sx={{
          alignItems: 'center',
          display: 'flex',
          height: 'fit-content',
          px: 2,
          mx: 1,
        }}
      >
        <Box
          sx={{
            flexGrow: 1,
            mx: 2,
          }}
        >
          <FormProvider {...form}>
            <form
              style={{ marginBottom: '5px' }}
              noValidate
            >
              <FormTextField
                multiline
                inputProps={{ maxLength: 1024 }}
                autoFocus
                name="message"
                placeholder={placeholder}
              />
            </form>
          </FormProvider>
          {description && (
            <Typography sx={{ px: 1, fontStyle: 'italic' }}>
              {description}
            </Typography>
          )}
        </Box>
      </Box>
    </AcceptCancelDialog>
  );
};

export default FormConfirmationDialogWithReason;
