import { FC } from 'react';
import { useFormContext, Controller } from 'react-hook-form';

import CloseIcon from '@material-hu/icons/material/Close';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import { SxProps } from '@material-hu/mui/styles';
import {
  DesktopDatePicker,
  DesktopDatePickerProps,
} from '@material-hu/mui/x-date-pickers/DesktopDatePicker';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { isMobileScreen } from 'src/utils/recognitions';

import { useTranslation } from '../i18n';

export type DatePickerControlProps = {
  name: string;
  label: string;
  defaultDate: Date | null;
  sx?: SxProps;
  showClearDate?: boolean;
  datePickerProps?: Partial<DesktopDatePickerProps<Date>>;
  fullWidth?: boolean;
};

export const DatePickerControl: FC<DatePickerControlProps> = props => {
  const {
    name,
    label,
    defaultDate,
    sx,
    showClearDate = true,
    datePickerProps,
    fullWidth,
  } = props;

  const { t } = useTranslation();
  const {
    control,
    formState: { errors },
  } = useFormContext();

  const fieldError = errors[name];

  return (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultDate}
      render={({ field }) => (
        <Box
          sx={{
            display: isMobileScreen() ? 'flex' : 'block',
            ...sx,
          }}
        >
          <DesktopDatePicker
            label={label}
            value={field.value}
            onChange={newValue => field.onChange(newValue)}
            slotProps={{
              textField: {
                fullWidth,
                error: !!fieldError,
                helperText: fieldError ? fieldError.message?.toString() : null,
              },
            }}
            {...datePickerProps}
          />
          {showClearDate && !isMobileScreen() && (
            <Button
              onClick={() => field.onChange(null)}
              sx={{ mt: 0.5 }}
            >
              {t('CLEAR_DATE')}
            </Button>
          )}
          {isMobileScreen() && (
            <IconButton
              sx={{ mr: 0.5 }}
              onClick={() => field.onChange(null)}
            >
              <CloseIcon />
            </IconButton>
          )}
        </Box>
      )}
    />
  );
};

export default DatePickerControl;
