"use client";

import { useEffect, useState } from "react";
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import { Fancybox as NativeFancybox } from "@fancyapps/ui";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  deleteOpportunityImage,
  downloadOpportunityImage,
  updateVolunteerOpportunityImages,
} from "@/features/opportunities/services/opportunities";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";
import type { VolunteerOpportunityDetail } from "./types";

/** The client's cap on photos added after an opportunity completes. */
export const MAX_COMPLETION_IMAGES = 10;

/**
 * Upload, delete and download for the post-completion gallery.
 *
 * Each of the three is a mutation plus its toasts plus a rule about when it is
 * allowed, which together were most of the component. The gallery itself is a
 * grid of thumbnails; this is what those thumbnails can have done to them.
 */
export function useCompletionGallery(
  data: VolunteerOpportunityDetail,
  isCreator: boolean,
  onChanged: () => void
) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);
  const [pendingFiles, setPendingFiles] = useState<File[]>([]);
  const [deletingImageId, setDeletingImageId] = useState<number | null>(null);

  const id = String(data.id);
  const galleryId = `opportunity-gallery-${id}`;

  const uploadMutation = useMutation({ mutationFn: updateVolunteerOpportunityImages });
  const deleteMutation = useMutation({ mutationFn: deleteOpportunityImage });
  const downloadMutation = useMutation({ mutationFn: downloadOpportunityImage });

  // Fancybox previews the gallery in place rather than in a new tab.
  useEffect(() => {
    const selectors = [galleryId].map(group => `[data-fancybox="${group}"]`);
    selectors.forEach(selector => NativeFancybox.bind(selector, {
      showClass: "fancybox-zoomIn",
      hideClass: "fancybox-zoomOut",
    }));
    return () => {
      selectors.forEach(selector => NativeFancybox.unbind(selector));
      NativeFancybox.close();
    };
  }, [galleryId]);

  const images = data.opportunity_images?.filter((image) => image.is_after_completed) ?? [];
  const isCompleted = data.opportunity_status === "completed";
  const canUpload = isCompleted && isCreator && images.length < MAX_COMPLETION_IMAGES;


  const upload = async (files: File[]) => {
    // Checked against the server's count, which also sees images another
    // session added since this page loaded.
    const remaining = MAX_COMPLETION_IMAGES - (data.after_completed_images_count || 0);
    if (files.length > remaining) {
      toast.error(t("COMMON.MAX_FILES_EXCEEDED"));
      setPendingFiles([]);
      return;
    }

    const formData = new FormData();
    files.forEach((file, index) => {
      formData.append(`new_opportunity_images_${index}`, file);
      formData.append(`new_opportunity_images_is_after_completed_${index}`, "true");
    });

    try {
      await uploadMutation.mutateAsync({ id, formData });
      toast.success(t("COMMON.TOAST.OPPORTUNITY_IMAGE_UPLOAD_SUCCESS"));
      setPendingFiles([]);
      onChanged();
    } catch (error) {
      console.error("Upload failed:", error);
      // The server's reason (size, type, the 10-image cap) when it gave one.
      toast.error(getApiErrorMessage(error, language, t("COMMON.TOAST.OPPORTUNITY_IMAGE_UPLOAD_FAILED")));
    }
  };

  const confirmDelete = async () => {
    if (!deletingImageId) return;
    try {
      await deleteMutation.mutateAsync({ image_ids: [deletingImageId], type: "volunteer" });
      toast.success(t("COMMON.TOAST.DELETE_IMAGE_SUCCESS"));
      setDeletingImageId(null);
      onChanged();
    } catch (error) {
      toast.error(getApiErrorMessage(error, language, t("COMMON.TOAST.DELETE_IMAGE_FAILED")));
    }
  };

  const download = async (imageId: number) => {
    if (downloadMutation.isPending) return; // one download at a time
    try {
      const { blob, filename } = await downloadMutation.mutateAsync({
        image_id: imageId,
        fallbackName: `opportunity_${data.id}`,
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      toast.success(t("COMMON.DOWNLOAD_SUCCESS"));
    } catch (error) {
      console.error("Download error:", error);
      toast.error(t("COMMON.DOWNLOAD_FAILURE"));
    }
  };

  return {
    galleryId,
    images,
    isCompleted,
    canUpload,
    pendingFiles,
    setPendingFiles,
    deletingImageId,
    setDeletingImageId,
    deleteMutation,
    upload,
    confirmDelete,
    download,
  };
}
