import React, { useEffect } from 'react';
import classNames from 'classnames/bind';
import styles from './InputImage.scss';
import FileUtil from '@src/utils/FileUtil';

const cx = classNames.bind(styles);

interface IOwnProps {
  title: string;
  imageRef: React.RefObject<HTMLImageElement> | null;
  videoRef?: React.RefObject<HTMLVideoElement> | null;
  setImage: (file: File | null) => void;
  limitFileSize?: number;
  fileTypes?: string[];
  fileSize?: { min: number; max: number };
  handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  disabled?: boolean;
};

const InputImage: React.FC<IOwnProps> = ({
  title,
  imageRef,
  videoRef,
  setImage,
  limitFileSize,
  fileTypes,
  fileSize,
  handleChange,
  disabled,
}) => {
  const handleChangeImg = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || !e.target.files[0]) {
      return;
    }

    const file = e.target.files[0];


    if (fileTypes && !FileUtil.fileTypeCheck(file, fileTypes)) {
      alert('파일 형식을 확인해 주십시오.');
      return;
    }

    if (limitFileSize && !FileUtil.fileSizeCheck(file, limitFileSize)) {
      alert('파일 크기를 확인해 주십시오.');
      return;
    }

    const reader = new FileReader();
    const img = new Image();

    reader.onload = e => {
      if (videoRef?.current && FileUtil.isVideo(file.name)) {
        videoRef.current.src = e.target?.result as string;
      } else {
        if (imageRef?.current) {
          imageRef.current.src = e.target?.result as string;
          img.src = e.target?.result as string;

          img.onload = () => {
            if (fileSize && (img.width < fileSize.min || img.height < fileSize.min || img.width > fileSize.max || img.height > fileSize.max)) {
              alert(`이미지 크기는 최소 ${fileSize.min}x${fileSize.min}, 최대  ${fileSize.max}x${fileSize.max}이어야 합니다.`);
              setImage(null);
              if (imageRef.current) {
                imageRef.current.src = '';
              }
              return;
            }
          };
        }
      }
    };

    reader.readAsDataURL(file);
    setImage(file);
    handleChange?.(e);

    e.currentTarget.value = '';
  };

  return (
    <div className={cx('input_image')}>
      <label htmlFor="profile_file" className={cx('label_file', disabled && 'disabled')}>{title}</label>
      <input id="profile_file" type="file" className={cx('input_file')} onChange={handleChangeImg} disabled={disabled} />
    </div>
  );
};

export default InputImage;
