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

const PhotoUpload2 = ({
  setFileUpload,
  maxFileSize = 2,
  maxWidth = 400,
  maxHeight = 400,
}) => {
  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);
      // if (!isValidDimensions) return;

      const formData = new FormData();
      formData.append("file", 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.`,
        5000,
        "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 = () => {
  //         if (image.width <= maxWidth && image.height <= maxHeight) {
  //           resolve(true);
  //         } else {
  //           showToast(
  //             globalDispatch,
  //             `Image dimensions exceed the maximum allowed dimensions (${maxWidth}x${maxHeight}).`,
  //             5000,
  //             'error'
  //           );
  //           resolve(false);
  //         }
  //       };
  //     };
  //     reader.readAsDataURL(file);
  //   });
  // };

  return (
    <div className={`flex max-w-full flex-col`}>
      <div className={`flex  max-w-[320px] flex-row gap-2`}>
        <input
          className="max-w-full rounded border border-gray-500 bg-gray-800 p-2 text-white shadow placeholder:text-gray-200"
          type="file"
          accept="image/*"
          onChange={saveFile}
        />
      </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 {maxWidth} x {maxHeight}&nbsp;pixels
      </div> */}
    </div>
  );
};

export default PhotoUpload2;
