import React from 'react';
import { GlobalContext, showToast } from '../globalContext';

const LogoUpload = ({
  setFileUpload,
  maxFileSize = 2,
  minWidth = 500,
  minHeight = 200,
  aspectRatioRange = [1.7, 3],
  transparent = false,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const saveFile = async (e) => {
    const file = e.target.files;
    if (file.length > 0) {
      if (!validateFileSize(file[0])) return;
      const isValidDimensions = await validateImageDimensions(file[0]);
      if (!isValidDimensions) return;
      else {
        const formData = new FormData();
        formData.append('files', file[0]);
        setFileUpload(formData);
      }
    }
  };

  const validateFileSize = (file) => {
    const fileSize = file.size / 1024 / 1024; // in MB
    if (fileSize > maxFileSize) {
      showToast(
        globalDispatch,
        `File size exceeds ${maxFileSize}MB. Please upload a smaller file.`,
        9000,
        'error'
      );
      return false;
    }
    return true;
  };

  const validateImageDimensions = (file) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = (event) => {
        const image = new Image();
        image.src = event.target.result;

        image.onload = () => {
          const aspectRatio = image.width / image.height;

          if (
            image.width >= minWidth &&
            image.height >= minHeight &&
            aspectRatio >= aspectRatioRange[0] &&
            aspectRatio <= aspectRatioRange[1]
          ) {
            resolve(true);
          } else if (
            aspectRatio <= aspectRatioRange[0] ||
            aspectRatio >= aspectRatioRange[1]
          ) {
            showToast(
              globalDispatch,
              `Image aspect ratio not within accepted range (16:9 - 3:1).`,
              5000,
              'error'
            );
            resolve(false);
          } else {
            showToast(
              globalDispatch,
              `Image dimensions exceed the maximum allowed dimensions (${minWidth}x${minHeight}).`,
              5000,
              'error'
            );
            resolve(false);
          }
        };
      };
      reader.readAsDataURL(file);
    });
  };

  return (
    <div className={`flex flex-col`}>
      <div className={`flex flex-row gap-2`}>
        <input
          className='rounded border border-gray-500 bg-gray-800 p-2 text-white shadow placeholder:text-gray-200'
          type='file'
          accept='image/*'
          onChange={saveFile}
        />
      </div>
      {transparent && (
        <div className='text-xs text-warning-600'>
          Logo with Transparent Background is recommended
        </div>
      )}
      <div className='text-xs text-warning-600'>
        Max file size limit is {maxFileSize}MB
      </div>
      <div className='text-xs text-warning-600'>
        Max file dimension is {minWidth} x {minHeight}&nbsp;pixels
      </div>

      <div className='text-xs text-warning-600'>
        Required Aspect ratio is 16:9 to 3:1
      </div>
    </div>
  );
};

export default LogoUpload;
