// form
import { useFormContext, Controller } from 'react-hook-form';
// @mui
import { FormHelperText, TextField } from '@mui/material';
import { DesktopDatePicker, LocalizationProvider } from '@mui/lab';
import AdapterDateFns from '@mui/lab/AdapterDateFns';

// ----------------------------------------------------------------------

interface IProps {
  name: string;
  label: string;
  dateFormat: string;
  fullWidth?: boolean;
  minDate?: any;
  maxDate?: any;
  disabled?: boolean;
}

export default function RHFDatePicker({ name, label, dateFormat, minDate, maxDate, disabled, ...other }: IProps) {
  const { control } = useFormContext();

  const { fullWidth } = other;

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Controller
        name={name}
        control={control}
        render={({ field, fieldState: { error } }) => (
          <>
            <DesktopDatePicker
              disabled={disabled}
              label={label}
              onChange={(date)=> field.onChange(date)}
              inputFormat={dateFormat}
              value={field.value}
              mask={''}
              minDate={(minDate) ? new Date(minDate) : null}
              maxDate={(maxDate) ? new Date(maxDate) : null}
              renderInput={(params) => <TextField
                fullWidth={fullWidth}
                {...params}
                />}
            />
            {!!error && (
              <FormHelperText error sx={{ px: 2 }}>
                {error.message}
              </FormHelperText>
            )}
          </>
        )}
      />
    </LocalizationProvider>
  );
}
