import React, { FC, memo, useRef } from 'react';
import { Controller, useForm } from 'react-hook-form';
import {
  Button,
  FormControl,
  FormErrorMessage,
  FormHelperText,
  FormLabel,
  HStack,
  Input,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';

import { landingApi } from '../../../__data__/service/landing.api';
import { UploadCarImage } from '../../../models/api';

import { useHandleUploadCarImageResponse } from './helper';

type FormValues = {
  carImg: File & {
    fileName: string;
  };
};

type CarImageFormProps = {
  orderId: UploadCarImage.Params['orderId'];
};

export const CarImageForm: FC<CarImageFormProps> = memo(function CarImageForm({
  orderId,
}) {
  const {
    handleSubmit,
    control,
    formState: { errors, isSubmitting },
  } = useForm<FormValues>({ shouldFocusError: true });

  const [uploadCarImage, uploadCarImageMutation] =
    landingApi.useUploadCarImageMutation();
  useHandleUploadCarImageResponse(uploadCarImageMutation);

  const onSubmit = (formData: FormValues) => {
    const body = new FormData();
    body.append('file', formData.carImg);
    uploadCarImage({ orderId, body });
  };

  const fileInputRef = useRef(null);

  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.order-view.upload-car-image',
  });

  return (
    <form>
      <FormControl>
        <FormLabel htmlFor='carImg'>{t('field.label')}</FormLabel>
        <Controller
          control={control}
          name='carImg'
          render={({ field: { value, onChange, ...field } }) => {
            return (
              <HStack gap={0}>
                <Input
                  {...field}
                  ref={fileInputRef}
                  accept='image/png,image/jpeg'
                  value={value?.fileName}
                  onChange={(event) => {
                    onChange(event.target.files[0]);
                    handleSubmit(onSubmit)();
                  }}
                  type='file'
                  hidden
                />
                <Input
                  placeholder={t('file-input.placeholder')}
                  value={value?.name || ''}
                  readOnly
                  borderRightRadius={0}
                />
                <Button
                  onClick={() => {
                    fileInputRef.current.click();
                  }}
                  isLoading={isSubmitting || uploadCarImageMutation.isLoading}
                  colorScheme='primary'
                  paddingInline={8}
                  borderLeftRadius={0}
                >
                  {t('file-input.button')}
                </Button>
              </HStack>
            );
          }}
        />
        <FormErrorMessage>{errors.carImg?.message}</FormErrorMessage>
        <FormHelperText>{t('field.help')}</FormHelperText>
      </FormControl>
    </form>
  );
});
