import React from "react";
import useCameraStore from "../hooks/useCameraStore";
import { IconButton } from "@mui/material";
import { LocalShipping } from "@mui/icons-material";

const MAX_WIDTH = 1024;
const JPEG_QUALITY = 0.7;

const DispatchCamera: React.FC = () => {
  const { setImageDispatch } = useCameraStore();

  const compressImage = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = () => {
        const img = new Image();
        img.onload = () => {
          let { width, height } = img;

          if (width > MAX_WIDTH) {
            height = (height * MAX_WIDTH) / width;
            width = MAX_WIDTH;
          }

          const canvas = document.createElement("canvas");
          canvas.width = width;
          canvas.height = height;

          const ctx = canvas.getContext("2d");
          if (!ctx) {
            reject("Canvas not supported");
            return;
          }

          ctx.drawImage(img, 0, 0, width, height);

          const compressedBase64 = canvas.toDataURL("image/jpeg", JPEG_QUALITY);

          resolve(compressedBase64);
        };

        img.onerror = reject;
        img.src = reader.result as string;
      };

      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };
  const handleCapture = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      const compressesd = await compressImage(file);
      setImageDispatch(compressesd);
    } catch (err) {
      console.error("Image compress failed", err);
    }
    // if (file) {
    //   const reader = new FileReader();
    //   reader.onloadend = () => {
    //     setImageDispatch(reader.result as string);
    //   };
    //   reader.readAsDataURL(file);
    // }
  };

  return (
    <div className="px-4 py-8 items-center border-2 rounded-md shadow-sm w-[49%] text-center ">
      <input
        type="file"
        accept="image/*"
        onChange={handleCapture}
        className="hidden"
        id="dispatchCameraInput"
      />
      <label htmlFor="dispatchCameraInput" className="text-gray-600">
        <IconButton
          color="primary"
          aria-label="upload picture"
          component="span"
        >
          <LocalShipping fontSize="large" />
        </IconButton>
        <br />
        Foto Dispatch
      </label>
    </div>
  );
};

export default DispatchCamera;
