import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import LocalMediaGrid from "../jobs-documents-local-gallery/local-media-grid.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import { fetchImgproxyThumbnails } from "./jobs-documents-imgproxy-gallery.component";

function JobsDocumentImgproxyGalleryExternal({ jobId, externalMediaState, context = "chat" }) {
  const [galleryImages, setgalleryImages] = externalMediaState;
  const [isLoading, setIsLoading] = useState(false);
  const { t } = useTranslation();

  const fetchThumbnails = useCallback(async () => {
    await fetchImgproxyThumbnails({ setStateCallback: setgalleryImages, jobId, imagesOnly: true });
  }, [jobId, setgalleryImages]);

  useEffect(() => {
    if (!jobId) return;
    setIsLoading(true);
    fetchThumbnails().finally(() => setIsLoading(false));
  }, [jobId, fetchThumbnails]);

  const handleToggle = useCallback(
    (idx) => {
      setgalleryImages((imgs) => imgs.map((g, gIdx) => (gIdx === idx ? { ...g, isSelected: !g.isSelected } : g)));
    },
    [setgalleryImages]
  );

  const messageStyle = { textAlign: "center", padding: "1rem" };

  if (!jobId) {
    return (
      <div aria-label="media gallery unavailable" style={{ position: "relative", minHeight: 80 }}>
        <div style={messageStyle}>No job selected.</div>
      </div>
    );
  }

  return (
    <div
      className="clearfix"
      style={{ position: "relative", minHeight: 80 }}
      data-jobid={jobId}
      aria-label={`media gallery for job ${jobId}`}
    >
      {isLoading && galleryImages.length === 0 && (
        <div className="local-gallery-loading" style={messageStyle} role="status" aria-live="polite">
          <LoadingSpinner />
        </div>
      )}
      {galleryImages.length > 0 && (
        <LocalMediaGrid images={galleryImages} minColumns={4} context={context} onToggle={handleToggle} />
      )}
      {galleryImages.length > 0 && (
        <div style={{ fontSize: 10, color: "#888", marginTop: 4 }} aria-live="off">
          {`${t("general.labels.media")}: ${galleryImages.length}`}
        </div>
      )}
    </div>
  );
}

export default JobsDocumentImgproxyGalleryExternal;
