import { type FC, useState } from 'react';

import { isString } from 'lodash-es';
import { type SxProps, type Theme } from '@material-hu/mui';
import { type TextFieldProps } from '@material-hu/mui/TextField';
import { DesktopDatePicker } from '@material-hu/mui/x-date-pickers/DesktopDatePicker';

import { useAuth } from 'src/contexts/JWTContext';
import { InputType } from 'src/types/forms';
import { simpleDateStringToLocalDate } from 'src/utils/date';
import { getDateFormat, getPlaceholderString } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

type DatePickerInputProps = {
  value?: string;
  onChange: () => void;
  disabled?: boolean;
  views?: any[];
  name?: string;
  inputType?: InputType;
  inputFormat?: string;
  textFieldProps?: TextFieldProps;
  datePickerProps?: Partial<any>;
  sxProps?: SxProps<Theme>;
};

const DatePickerInput: FC<DatePickerInputProps> = ({
  value,
  onChange,
  views,
  name,
  inputType,
  inputFormat,
  textFieldProps,
  datePickerProps,
  sxProps,
  ...rest
}) => {
  const { t } = useLokaliseTranslation('forms');
  const { user } = useAuth();

  const [open, setOpen] = useState(false);

  const placeholderString = getPlaceholderString(views, inputType);
  const dateFormat = getDateFormat(user, inputType);

  return (
    <DesktopDatePicker
      views={views}
      {...(inputFormat ? { format: inputFormat } : {})}
      value={
        isString(value) ? simpleDateStringToLocalDate(value) : value || null
      }
      onChange={onChange}
      open={open}
      onOpen={() => setOpen(true)}
      onClose={() => setOpen(false)}
      {...datePickerProps}
      {...rest}
      slotProps={{
        textField: {
          sx: { width: '100%', ...sxProps },
          onClick: () => setOpen(true),
          helperText: '',
          inputProps: {
            placeholder: t(placeholderString, { dateFormat: dateFormat }),
          },
          ...textFieldProps,
        },
      }}
    />
  );
};

export default DatePickerInput;
