"use client";


import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { FiDownload } from "react-icons/fi";
import { MdDelete } from "react-icons/md";
import ConfirmModal from "@/components/ui/ConfirmModal";
import UploadImageWithSave from "@/components/ui/UploadImageWithSave";
import {
  IMAGE_UPLOAD_ACCEPT,
  isAllowedImageUpload,
} from "@/features/shared/imageUploadRules";
import { useLanguageStore } from "@/store/languageStore";
import {
  MAX_COMPLETION_IMAGES,
  useCompletionGallery,
} from "./useCompletionGallery";
import type { VolunteerOpportunityDetail } from "./types";
import AssetIcon from "@/components/ui/AssetIcon";
import CoverImage from "@/components/ui/CoverImage";

interface CompletionGalleryProps {
  data: VolunteerOpportunityDetail;
  isCreator: boolean;
  onChanged: () => void;
}

/**
 * Photos from the day, added by the creator once the opportunity is complete.
 * Anyone can view and download them; only the creator uploads or deletes.
 *
 * Separate from the announcement image, which is single and cropped 1:1 on the
 * publish form (BE-76). This gallery is unlimited in kind but capped at ten.
 */
export default function CompletionGallery({
  data,
  isCreator,
  onChanged,
}: CompletionGalleryProps) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);
  const {
    galleryId,
    images,
    canUpload,
    pendingFiles,
    setPendingFiles,
    deletingImageId,
    setDeletingImageId,
    deleteMutation,
    upload,
    confirmDelete,
    download,
  } = useCompletionGallery(data, isCreator, onChanged);

  const isCompleted = data.opportunity_status === "completed";
  if (!(isCompleted && isCreator) && images.length === 0) return null;


  return (
    <>
      <div className="pt-6">
        {(canUpload || images.length > 0) && (
          <h3 className="text-sm md:text-base font-bold text-primary-5 mb-3 flex gap-2 items-center">
            <div dir="rtl">
              <AssetIcon
                src="/assets/voluneteerevent/rightarrows.svg"
                size={22}
                className={language === "ar" ? "rotate-rtl" : ""}
              />
            </div>
            {t("COMMON.OPPORTUNITY_IMAGE")}
          </h3>
        )}

        {canUpload && (
          <div>
            <UploadImageWithSave
              label={t("COMMON.UPLOAD_IMAGE")}
              instructions={[t("COMMON.REVIEW_IMAGE_LIMIT")]}
              multiple
              accept={IMAGE_UPLOAD_ACCEPT}
                isFileAllowed={isAllowedImageUpload}
                invalidMessage={t("COMMON.REVIEW_IMAGE_LIMIT")}
              value={pendingFiles}
              onChange={(files) => {
                if (files.length > MAX_COMPLETION_IMAGES - images.length) {
                  toast.error(t("COMMON.MAX_FILES_EXCEEDED"));
                  return;
                }
                setPendingFiles(files);
              }}
              onRemove={(index) =>
                setPendingFiles((previous) => previous.filter((_, i) => i !== index))
              }
              onSave={() =>
                pendingFiles.length > 0 ? upload(pendingFiles) : undefined
              }
            />
          </div>
        )}
      </div>

      {images.length > 0 && (
        <div className="relative mt-6">
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-5">
            {images.map((image) => (
              <div key={image.id} className="relative group">
                {/* `aspect-square relative` moves from the image onto the
                    anchor so the tile's height comes from the grid, not from
                    the photo — the lightbox anchor still wraps it. */}
                <a
                  href={image.image}
                  data-fancybox={galleryId}
                  className="relative block aspect-square w-full cursor-zoom-in rounded-lg"
                  title={t("COMMON.CLICK_TO_VIEW")}
                >
                  <CoverImage
                    src={image.image}
                    alt={t("COMMON.COMPLETED_OPPORTUNITY_IMAGE")}
                    className="rounded-lg object-cover"
                    sizes="(min-width: 1024px) 25vw, 50vw"
                  />
                </a>
                <div className={`absolute top-2 right-2 ${isCreator ? "flex gap-2" : ""}`}>
                  <button
                    type="button"
                    className="w-6 h-6 flex items-center justify-center rounded-full border border-blue-400 bg-white text-blue-500 opacity-0 group-hover:opacity-100 transition-opacity shadow hover:bg-blue-100"
                    onClick={() => download(image.id)}
                    title={t("COMMON.DOWNLOAD_IMAGE")}
                  >
                    <FiDownload size={14} />
                  </button>
                  {isCreator && (
                    <button
                      type="button"
                      className="w-6 h-6 flex items-center justify-center rounded-full border border-red-400 bg-white text-red-500 opacity-0 group-hover:opacity-100 transition-opacity shadow hover:bg-red-100"
                      onClick={() => setDeletingImageId(image.id)}
                      title={t("COMMON.DELETE_IMAGE")}
                    >
                      <MdDelete size={14} />
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      <ConfirmModal
        open={deletingImageId !== null}
        onClose={() => setDeletingImageId(null)}
        title={t("COMMON.DELETE_IMAGE")}
        message={t("COMMON.ARE_YOU_SURE_DELETE_IMAGE")}
        onConfirm={confirmDelete}
        isPending={deleteMutation.isPending}
      />
    </>
  );
}
