import {
  type DropEvent,
  type ErrorCode,
  type FileRejection,
} from 'react-dropzone';
import { Controller, useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { bytesToSize } from '../../../utils/bytes';

import { type FormCoverPictureUploaderProps } from './types';
import CoverPictureUploader from '.';

const FormCoverPictureUploader = ({
  name,
  uploaderProps = {},
  rules,
}: FormCoverPictureUploaderProps) => {
  const { t } = useTranslation('material_hu_only');
  const form = useFormContext();

  const handleDropAccepted = (file: File, event: DropEvent) => {
    uploaderProps.onDropAccepted?.(file, event);
    form.clearErrors();
  };

  const handleDropRejected = (
    filesRejected: FileRejection[],
    event: DropEvent,
  ) => {
    uploaderProps.onDropRejected?.(filesRejected, event);

    if (!filesRejected?.length && !filesRejected[0]?.errors?.length) return;

    const errorCode = filesRejected[0].errors[0].code as ErrorCode;

    form.setError(name, {
      type: 'custom',
      message: t('cover_picture_uploader.cover_picture_error', {
        context: errorCode,
        max: bytesToSize(uploaderProps.maxSize),
        count: 1,
      }),
    });
  };

  return (
    <Controller
      name={name}
      rules={rules}
      render={({ field, fieldState }) => {
        return (
          <CoverPictureUploader
            {...field}
            {...uploaderProps}
            error={!!fieldState.error}
            helperText={fieldState.error?.message || uploaderProps.helperText}
            onDropAccepted={handleDropAccepted}
            onDropRejected={handleDropRejected}
            onFileChange={uploaderProps.onFileChange}
          />
        );
      }}
    />
  );
};

export default FormCoverPictureUploader;
