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

const compressImage = (
  file: File,
  maxWidth = 1600,
  quality = 0.6
): Promise<string> => {
  return new Promise((resolve) => {
    const img = new Image();
    const reader = new FileReader();

    reader.onload = () => {
      img.src = reader.result as string;
    };

    img.onload = () => {
      const scale = Math.min(1, maxWidth / img.width);
      const canvas = document.createElement("canvas");

      canvas.width = img.width * scale;
      canvas.height = img.height * scale;

      const ctx = canvas.getContext("2d")!;
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

      resolve(canvas.toDataURL("image/jpeg", quality));
    };

    reader.readAsDataURL(file);
  });
};

const SjCamera: React.FC = () => {
  const { setImageSj } = useCameraStore();
  const fileRef = useRef<HTMLInputElement | null>(null);

  const handleSuratJalanCapture = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const imgs = await Promise.all(
      Array.from(event.target.files ?? []).map((file) =>
        compressImage(file, 1600, 0.6)
      )
    );

    imgs.forEach((img) => setImageSj(img));

    if (fileRef.current) fileRef.current.value = "";
  };

  return (
    <div className="p-4 py-8 items-center border-2 rounded-md shadow-sm w-[49%] text-center">
      <input
        ref={fileRef}
        id="suratJalanInput"
        type="file"
        accept="image/*"
        multiple
        capture="environment"
        className="hidden"
        onChange={handleSuratJalanCapture}
      />
      <label
        htmlFor="suratJalanInput"
        className="text-gray-600 cursor-pointer select-none"
      >
        <IconButton color="primary" component="span">
          <PendingActions fontSize="large" />
        </IconButton>
        <br />
        Foto Surat Jalan
      </label>
    </div>
  );
};

export default SjCamera;
