import { useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

import HelpOutlineIcon from '@material-hu/icons/material/HelpOutline';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import {
  CustomDueDatePeriod,
  CustomDueDateRelation,
  DueDateType,
} from 'src/types/onboarding';
import { insertIf } from 'src/utils/arrayUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormRadioGroup from 'src/components/FormInputs/FormRadioGroup';
import FormSelect from 'src/components/FormInputs/FormSelect';
import FormTextField from 'src/components/FormInputs/FormTextField';

import { validateDates } from './utils';

const StyledStack = styled(Stack)(({ theme }) => ({
  gap: theme.spacing(1),
  flexDirection: 'row',
  alignItems: 'center',
}));

type Props = {
  customDateType: string;
  autoAssign?: boolean;
};

function DateSelection({ customDateType, autoAssign = false }: Props) {
  const { t } = useLokaliseTranslation('onboarding');
  const form = useFormContext();
  const selectedType = form.watch(customDateType);
  const { autoAssignDate } = form.watch();
  const autoAssignHasErrors = !!form.getFieldState(
    'autoAssignDate.customAssignDate.toDateAmount',
    form.formState,
  ).error;

  const getFormAmount = (name: string) => (
    <FormTextField
      name={name}
      type="number"
      size="small"
      sx={{ width: 100 }}
      label={t('amount')}
      InputProps={{
        inputProps: { min: 0 },
      }}
    />
  );

  const getFormPeriod = (name: string) => (
    <FormSelect
      name={name}
      options={Object.keys(CustomDueDatePeriod).map(period => ({
        label: t(`custom_due_date_period_${period}`),
        value: period,
      }))}
      formControlProps={{ size: 'small' }}
      adaptWidthToOptions
      label={t('time')}
    />
  );

  const getFormRelation = (name: string) => (
    <FormSelect
      name={name}
      options={Object.keys(CustomDueDateRelation).map(relation => ({
        label: t(`custom_due_date_relation_${relation}`),
        value: relation,
      }))}
      formControlProps={{ size: 'small' }}
      adaptWidthToOptions
      label={t('sequence')}
    />
  );

  useEffect(() => {
    if (
      autoAssignDate.autoAssignDateType === DueDateType.CUSTOM &&
      !validateDates(autoAssignDate)
    ) {
      if (!autoAssignHasErrors) {
        form.setError('autoAssignDate.customAssignDate.toDateAmount', {});
      }
    } else {
      form.trigger('autoAssignDate.customAssignDate.toDateAmount');
    }
  }, [JSON.stringify(autoAssignDate), autoAssignHasErrors]);

  return (
    <>
      <FormRadioGroup
        column
        name={customDateType}
        options={[
          ...insertIf(!autoAssign, {
            label: t(`due_date_type_${DueDateType.NO_DUE_DATE}`),
            value: DueDateType.NO_DUE_DATE,
          }),
          ...insertIf(autoAssign, {
            label: t(`due_date_type_${DueDateType.HIRE_DATE}`),
            value: DueDateType.HIRE_DATE,
          }),
          ...insertIf(!autoAssign, {
            label: (
              <StyledStack>
                {getFormAmount('dueDate.customDueDateAmount')}
                {getFormPeriod('dueDate.customDueDatePeriod')}
                {getFormRelation('dueDate.customDueDateRelation')}
                <Typography>{t('from_hire_date')}</Typography>
              </StyledStack>
            ),
            value: DueDateType.CUSTOM,
          }),
          ...insertIf(autoAssign, {
            label: (
              <StyledStack>
                {t(`due_date_type_${DueDateType.RIGHT_NOW}`)}
                <Tooltip title={t('right_now_tooltip')}>
                  <HelpOutlineIcon fontSize="small" />
                </Tooltip>
              </StyledStack>
            ),
            value: DueDateType.RIGHT_NOW,
          }),
          ...insertIf(autoAssign, {
            label: t('range'),
            value: DueDateType.CUSTOM,
          }),
        ]}
      />
      {autoAssign && selectedType === DueDateType.CUSTOM && (
        <>
          <Stack sx={{ gap: 1 }}>
            <StyledStack>
              <Typography>{t('from')}</Typography>
              {getFormAmount('autoAssignDate.customAssignDate.fromDateAmount')}
              {getFormPeriod('autoAssignDate.customAssignDate.fromDatePeriod')}
              {getFormRelation(
                'autoAssignDate.customAssignDate.fromDateRelation',
              )}
              <Typography>{t('from_hire_date')}</Typography>
            </StyledStack>
            <StyledStack>
              <Typography>{t('to')}</Typography>
              {getFormAmount('autoAssignDate.customAssignDate.toDateAmount')}
              {getFormPeriod('autoAssignDate.customAssignDate.toDatePeriod')}
              {getFormRelation(
                'autoAssignDate.customAssignDate.toDateRelation',
              )}
              <Typography>{t('from_hire_date')}</Typography>
            </StyledStack>
          </Stack>
          {autoAssignHasErrors && (
            <Typography
              color="error"
              sx={{ mt: 1 }}
            >
              {t('autoassign_date_error')}
            </Typography>
          )}
        </>
      )}
    </>
  );
}
export default DateSelection;
