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

import Stack from '@material-hu/mui/Stack';
import { SxProps, Theme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  validateIsAfterDate,
  validateIsBeforeDate,
  validateTimeRequiredRule,
} from 'src/utils/validation';

import FormTimePicker from 'src/components/FormInputs/FormTimePicker';

type Props = {
  containerSx?: SxProps<Theme>;
};

const inputStyle: SxProps = {
  flex: 1,
};

const WorkingHoursSelector: FC<Props> = props => {
  const { containerSx } = props;
  const parentForm = useFormContext();
  const { t } = useLokaliseTranslation('work_schedules');

  const { checkIn, checkOut } = parentForm.watch();

  useEffect(() => {
    if (checkIn && checkOut) {
      parentForm.trigger();
    }
  }, [checkIn, checkOut]);

  return (
    <Stack sx={{ mb: 4, ...containerSx }}>
      <Typography
        variant="subtitle1"
        sx={{ mb: 1 }}
      >
        {t('WORK_SCHEDULE')}
      </Typography>
      <Typography
        variant="body1"
        sx={{
          color: theme => theme.palette.text.secondary,
          mb: 2,
        }}
      >
        {t('WORK_SCHEDULE_HINT')}
      </Typography>
      <Stack
        sx={{
          alignItems: 'center',
          flexDirection: 'row',
          height: '80px',
          justifyContent: 'space-between',
          width: '100%',
        }}
      >
        <FormTimePicker
          name="checkIn"
          label={t('CHECK_IN')}
          textFieldProps={{ sx: inputStyle }}
          validateRules={{
            required: validateTimeRequiredRule(),
            beforeCheckout: validateIsBeforeDate(checkOut, t('ERROR_BEFORE')),
          }}
        />
        <Typography
          variant="body1"
          sx={{ mx: 2 }}
        >
          {t('TO')}
        </Typography>
        <FormTimePicker
          name="checkOut"
          label={t('CHECK_OUT')}
          textFieldProps={{ sx: inputStyle }}
          validateRules={{
            required: validateTimeRequiredRule(),
            afterCheckIn: validateIsAfterDate(checkIn, t('ERROR_AFTER')),
          }}
        />
      </Stack>
    </Stack>
  );
};

export default WorkingHoursSelector;
