import { LabeledInput } from '@/components/ra-inputs/LabeledInput';
import { styled } from '@mui/material/styles';
import dayjs from 'dayjs';
import { useCallback, useState } from 'react';
import { DateInputProps, DateInput as RaDateInput } from 'react-admin';

const MAX_YEAR_LENGTH = 4;

const StyledDateInput = styled(RaDateInput, { slot: 'root' })(({ label }) => ({
  '& legend': {
    width: label === false ? 0 : 'auto'
  }
}));

function DateInput(props: DateInputProps): JSX.Element {
  const [dateValue, setDateValue] = useState('');

  const handleInput = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const nextValue = event.target.value;
      const year = dayjs(nextValue).year();

      if (year.toString().length > MAX_YEAR_LENGTH) {
        event.target.value = dateValue;
      } else {
        setDateValue(nextValue);
      }
    },
    [dateValue]
  );

  return (
    // @ts-ignore
    <LabeledInput {...props}>
      <StyledDateInput {...props} onInput={handleInput} />
    </LabeledInput>
  );
}

export { DateInput };
export type { DateInputProps };
