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

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

  const readFilesAsDataURL = (files: FileList | null): Promise<string[]> =>
    new Promise((resolve) => {
      if (!files || files.length === 0) return resolve([]);
      const list = Array.from(files);
      const out: string[] = [];
      let done = 0;
      list.forEach((f) => {
        const fr = new FileReader();
        fr.onload = (e) => {
          const dataUrl = (e.target?.result as string) || "";
          if (dataUrl) out.push(dataUrl);
          done += 1;
          if (done === list.length) resolve(out);
        };
        fr.onerror = () => {
          done += 1;
          if (done === list.length) resolve(out);
        };
        fr.readAsDataURL(f);
      });
    });

  const handleSuratJalanCapture = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const imgs = await readFilesAsDataURL(event.target.files);
    if (imgs.length > 0) {
      // APPEND: panggil setImageSj untuk tiap foto
      imgs.forEach((img) => setImageSj(img));
    }
    // reset supaya bisa pilih file yang sama lagi
    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
        className="hidden"
        onChange={handleSuratJalanCapture}
      />
      <label
        htmlFor="suratJalanInput"
        className="text-gray-600 cursor-pointer select-none"
      >
        <IconButton
          color="primary"
          aria-label="upload picture"
          component="span"
        >
          <PendingActions fontSize="large" />
        </IconButton>
        <br />
        Foto Surat Jalan
      </label>
    </div>
  );
};

export default SjCamera;
