import {useMemo} from 'react';
import {useTranslation} from 'react-i18next';
import {Accordion, InputDate} from '@components/_HuGo';
import {Language} from '@config/i18n';
import {getDate} from '@shared/utils';

import {styles} from './styles';

interface Props {
  error: boolean;
  fromDate: Nullable<Date>;
  onChangeFromDate: (date: Nullable<Date>) => void;
  onChangeToDate: (date: Nullable<Date>) => void;
  toDate: Nullable<Date>;
  title: string;
}

export function DatesFilter({
  error,
  fromDate,
  onChangeFromDate,
  onChangeToDate,
  toDate,
  title,
}: Props) {
  const {i18n, t} = useTranslation();

  const datePlaceholder = useMemo(
    () => (i18n.language === Language.En ? 'MM/DD/YYYY' : 'DD/MM/YYYY'),
    [i18n.language],
  );

  const dateDescription = useMemo(() => {
    const fromDateString = getDate(fromDate, i18n.language);
    const toDateString = getDate(toDate, i18n.language);
    return fromDate && toDate
      ? `${t('time_off.from')} ${fromDateString} ${t(
          'time_off.until',
        ).toLowerCase()} ${toDateString}`
      : fromDate
      ? `${t('time_off.from')} ${fromDateString}`
      : toDate
      ? `${t('time_off.until')} ${toDateString}`
      : undefined;
  }, [fromDate, toDate, i18n.language, t]);

  const onClearFromDate = () => {
    onChangeFromDate(null);
  };

  const onClearToDate = () => {
    onChangeToDate(null);
  };

  return (
    <Accordion style={styles.container}>
      <Accordion.Header>
        <Accordion.Title title={title} description={dateDescription} />
        <Accordion.Icon />
      </Accordion.Header>
      <Accordion.Content>
        <InputDate
          label={t('time_off.from')}
          onChange={onChangeFromDate}
          onClear={onClearFromDate}
          placeholder={datePlaceholder}
          value={fromDate || undefined}
        />
        <InputDate
          helper={error ? t('time_off.invalid_date') : ''}
          isError={error}
          label={t('time_off.until')}
          onChange={onChangeToDate}
          onClear={onClearToDate}
          minDate={fromDate || undefined}
          placeholder={datePlaceholder}
          value={toDate || undefined}
        />
      </Accordion.Content>
    </Accordion>
  );
}
