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

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import {
  DesktopDatePicker,
  type DesktopDatePickerProps,
} from '@material-hu/mui/x-date-pickers/DesktopDatePicker';

import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = {
  name: string;
  label: string;
  fullWidth?: boolean;
  defaultDate: Date | null;
  errors?: string[];
  datePickerProps?: Partial<DesktopDatePickerProps<Date>>;
};

const FormDatePicker: FC<Props> = ({
  name,
  label,
  defaultDate,
  datePickerProps,
  fullWidth = true,
  errors = [],
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultDate}
      render={({ field }) => (
        <Stack sx={{ gap: 0.5 }}>
          <DesktopDatePicker
            label={label}
            value={field.value}
            onChange={newValue => field.onChange(newValue)}
            slotProps={{
              textField: {
                fullWidth,
                error: errors.length > 0,
                inputProps: {
                  placeholder: t('date_format'),
                },
              },
            }}
            {...datePickerProps}
          />
          {errors.length > 0 && (
            <Stack>
              {errors.map(err => (
                <Typography
                  key={err}
                  variant="caption"
                  color="error"
                >
                  {err}
                </Typography>
              ))}
            </Stack>
          )}
        </Stack>
      )}
    />
  );
};

export default FormDatePicker;
