import React, { useCallback, useEffect, useState } from 'react';
import type { ChangeEventHandler, Dispatch, MouseEventHandler, SetStateAction } from 'react';
import InputMask from 'react-input-mask';
import clsx from 'clsx';

import TextField from '@mui/material/TextField';
import IconButton from '@mui/material/IconButton';

import { ASSETS_URL } from '../../../../../consts/common';
import { CustomIcon } from '../../../../custom-icon';

import { autoInputDate, parserInputValueDate } from './helpers';
import { textToDateDMY } from '../helpers';
import createClasses from './styles';

const defaultValue = '__/__/____ - __/__/____';

export interface HeaderDatePickerProps {
  handleOpen: (newState?: boolean) => void | MouseEventHandler<HTMLButtonElement>;
  handleClear: () => void;
  placeholder?: string;
  startDate?: Date | null;
  endDate?: Date | null;
  setStartDate: Dispatch<SetStateAction<Date | null>>;
  setEndDate: Dispatch<SetStateAction<Date | null>>;
  open: boolean;
  id: string;
  fieldFocus: boolean;
  toggleFieldFocus: (nextValue?: unknown) => void;
}

const HeaderDatePicker = (props: HeaderDatePickerProps) => {
  const {
    handleOpen,
    handleClear,
    placeholder = 'Pick a date',
    startDate = null,
    endDate = null,
    setStartDate,
    setEndDate,
    open,
    id,
    fieldFocus,
    toggleFieldFocus
  } = props;

  const styles = createClasses();

  const [value, setValue] = useState('');
  useEffect(() => {
    if (startDate) {
      setValue(textToDateDMY(startDate, endDate));
    } else {
      setValue('');
    }
  }, [startDate, endDate]);

  useEffect(() => {
    const inputDate = parserInputValueDate(value);
    if (inputDate) {
      setStartDate(inputDate.start);
      setEndDate(inputDate.end);
    }
    // eslint-disable-next-line
  }, [value]);

  const onChangeInput: ChangeEventHandler<HTMLInputElement> = e => {
    setValue(autoInputDate(value, e.target.value));
  };

  const handleClearInput: MouseEventHandler = useCallback(() => {
    setValue('');
    handleClear();
  }, [handleClear]);

  const handleFocus = useCallback(() => {
    toggleFieldFocus(true);
    handleOpen(false);
  }, [handleOpen, toggleFieldFocus]);

  const handleBlur = useCallback(() => {
    toggleFieldFocus(false);
  }, [toggleFieldFocus]);

  return (
    <InputMask
      mask="99/99/9999 - 99/99/9999"
      onChange={onChangeInput}
      value={value}
      onFocus={handleFocus}
      onBlur={handleBlur}
      id={id}
      date-testid="inputMask"
    >
      {() => (
        <TextField
          className={styles.textField}
          fullWidth
          placeholder={placeholder}
          focused={fieldFocus}
          InputProps={{
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            'data-testid': 'textField',
            endAdornment: (
              <>
                {value && value !== defaultValue && (
                  <IconButton
                    data-testid="clearIcon"
                    size="small"
                    onClick={handleClearInput}
                    aria-label="Clear field"
                    className={styles.endAdornmentButton}
                  >
                    <CustomIcon
                      color="inherit"
                      src={`${ASSETS_URL}/icons/icon_closeCircle.svg`}
                      className={clsx(styles.endAdornment, styles.clearIcon)}
                    />
                  </IconButton>
                )}

                <IconButton
                  aria-hidden="true"
                  data-testid="openIcon"
                  onClick={handleOpen as unknown as MouseEventHandler<HTMLButtonElement>}
                  className={styles.endAdornmentButton}
                  size="large"
                >
                  <CustomIcon
                    color="inherit"
                    src={`${ASSETS_URL}/icons/icon_arrow.svg`}
                    className={clsx(styles.endAdornment, open && styles.rotateIcon)}
                  />
                </IconButton>
              </>
            )
          }}
        />
      )}
    </InputMask>
  );
};

export default HeaderDatePicker;
