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

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

import FormTimePicker from '@material-hu/components/composed-components/TimePicker/form';
import HuAlert from '@material-hu/components/design-system/Alert';

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

import { workScheduleFields } from '../../../form';
import { SCHEDULES_ERROR_MESSAGES } from '../../constants';
import { type ScheduleFields, type TimeSlotError } from '../../types';
import { omitInNightShifts } from '../../utils';

type Props = {
  enabledNightShifts: boolean;
};

const GeneralTimeSlot = (props: Props) => {
  const { enabledNightShifts } = props;
  const { t } = useLokaliseTranslation(['work_schedules', 'general', 'shifts']);
  const {
    formState: { errors },
    trigger,
    watch,
  } = useFormContext<ScheduleFields>();
  const { generalTimeSlots } = watch();

  const timeSlot = generalTimeSlots[0];

  useEffect(() => {
    trigger();
  }, [timeSlot.startTime, timeSlot.endTime]);

  const timeSlotErrors = errors?.generalTimeSlots?.[0] as
    | TimeSlotError
    | undefined;
  const currentError =
    timeSlotErrors &&
    timeSlotErrors[Object.keys(timeSlotErrors)[0] as keyof TimeSlotError];
  const hideFieldError =
    currentError?.type === 'dateOrder' || currentError?.type === 'equalDates';

  const creatingNightShift =
    enabledNightShifts &&
    timeSlot.startTime &&
    timeSlot.endTime &&
    timeSlot.startTime > timeSlot.endTime;

  return (
    <Stack
      sx={{
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%',
      }}
    >
      <Stack
        sx={{
          alignItems: 'baseline',
          backgroundColor: ({ palette }) =>
            palette.new.background.elements.grey,
          borderRadius: '16px',
          flexDirection: 'row',
          justifyContent: 'space-between',
          p: 2,
          width: '100%',
        }}
      >
        <FormTimePicker
          name={workScheduleFields.generalTimeSlots.start(0)}
          inputProps={{
            placeholder: t('shifts:entry_hour'),
            hideErrorText: hideFieldError,
            fullWidth: true,
          }}
          rules={{
            validate: {
              completeSchedule: timeSlot.endTime
                ? validateTimeRequiredRule()
                : () => true,
              equalDates: validateIsSameDate(
                timeSlot.endTime,
                t('work_schedules:error_same_date'),
              ),
              dateOrder: omitInNightShifts(
                enabledNightShifts,
                validateIsBeforeDate(
                  timeSlot.endTime,
                  t('work_schedules:error_date_order'),
                ),
              ),
            },
          }}
        />
        <Typography
          variant="globalS"
          sx={{ mx: 2 }}
        >
          {t('TO')}
        </Typography>
        <FormTimePicker
          name={workScheduleFields.generalTimeSlots.end(0)}
          inputProps={{
            placeholder: t('shifts:exit_hour'),
            hideErrorText: hideFieldError,
            fullWidth: true,
          }}
          rules={{
            validate: {
              completeSchedule: timeSlot.startTime
                ? validateTimeRequiredRule()
                : () => true,
              equalDates: validateIsSameDate(
                timeSlot.startTime,
                t('work_schedules:error_same_date'),
              ),
              dateOrder: omitInNightShifts(
                enabledNightShifts,
                validateIsAfterDate(
                  timeSlot.startTime,
                  t('work_schedules:error_date_order'),
                ),
              ),
            },
          }}
        />
      </Stack>
      {hideFieldError && (
        <HuAlert
          severity="warning"
          title={t(
            SCHEDULES_ERROR_MESSAGES[
              currentError.type as keyof typeof SCHEDULES_ERROR_MESSAGES
            ].title,
          )}
          description={t(
            SCHEDULES_ERROR_MESSAGES[
              currentError.type as keyof typeof SCHEDULES_ERROR_MESSAGES
            ].description,
          )}
          sx={{
            mt: 2,
            '&.MuiPaper-root': {
              width: '100%',
            },
          }}
        />
      )}
      {creatingNightShift && (
        <HuAlert
          severity="info"
          title={t('NIGHT_SHIFT')}
          description={t('NIGHT_SHIFT_DESCRIPTION')}
          sx={{ mt: 2 }}
        />
      )}
    </Stack>
  );
};

export default GeneralTimeSlot;
