"use client";

import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { FiDownload } from "react-icons/fi";
import { MdDelete } from "react-icons/md";
import UploadImageWithSave from "@/components/ui/UploadImageWithSave";
import {
  IMAGE_UPLOAD_ACCEPT,
  isAllowedImageUpload,
} from "@/features/shared/imageUploadRules";
import AssetIcon from "@/components/ui/AssetIcon";
import CoverImage from "@/components/ui/CoverImage";

/** The cap the backend enforces on post-completion images. */
const MAX_IMAGES = 10;

interface GalleryImage {
  id: number;
  image?: string;
}

interface LearnServeCompletionGalleryProps {
  id: string;
  isCreator: boolean;
  selectedLanguage: string;
  opportunityStatus?: string;
  opportunityRecordId?: string | number;
  afterCompletedImages: GalleryImage[];
  pendingFiles: File[];
  setPendingFiles: (
    files: File[] | ((previous: File[]) => File[])
  ) => void;
  /** Returns the upload, so «حفظ» stays disabled until it settles. */
  onUpload: (files: File[]) => void | Promise<unknown>;
  onDownload: (imageId: number, imageName?: string) => void;
  onDelete: (imageId: number) => void;
}

/**
 * The photos added *after* the opportunity finished: the creator's uploader
 * while it is under the cap, and the grid everyone sees.
 *
 * Card artwork is excluded: this gallery only contains completion photos.
 */
export default function LearnServeCompletionGallery({
  id,
  isCreator,
  selectedLanguage,
  opportunityStatus,
  opportunityRecordId,
  afterCompletedImages,
  pendingFiles,
  setPendingFiles,
  onUpload,
  onDownload,
  onDelete,
}: LearnServeCompletionGalleryProps) {
  const { t } = useTranslation();
  const isCompleted = opportunityStatus === "completed";
  const canUpload =
    isCompleted && isCreator && afterCompletedImages.length < MAX_IMAGES;

  return (
    <>
      {/* Post-completion gallery: creators can add up to 10 images */}
      {((isCompleted && isCreator) || afterCompletedImages.length > 0) && (
        <div className="pt-[50px] pb-2">
          {(canUpload || afterCompletedImages.length > 0) && (
            <h3 className="2xl:text-xl lg:text-base 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={selectedLanguage === "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) => {
                  const remainingSlots =
                    MAX_IMAGES - afterCompletedImages.length;
                  if (files.length > remainingSlots) {
                    toast.error(t("COMMON.MAX_FILES_EXCEEDED"));
                    return;
                  }
                  setPendingFiles(files);
                }}
                onRemove={(index) =>
                  setPendingFiles((previous) =>
                    previous.filter((_, i) => i !== index)
                  )
                }
                onSave={() =>
                  pendingFiles.length > 0 ? onUpload(pendingFiles) : undefined
                }
              />
            </div>
          )}
        </div>
      )}

      {afterCompletedImages.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">
            {afterCompletedImages.map((image) => (
              <div key={image.id} className="relative group">
                <a
                  href={image.image}
                  data-fancybox={`opportunity-gallery-${id}`}
                  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={() =>
                      onDownload(image.id, `opportunity_${opportunityRecordId}`)
                    }
                    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={() => onDelete(image.id)}
                      title={t("COMMON.DELETE_IMAGE")}
                    >
                      <MdDelete size={14} />
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
}
