"use client";

import { toast } from "sonner";
import { type LearnServeDetailsData } from "./useLearnServeDetailsData";
import { type LearnServeDialogs } from "./useLearnServeDialogs";
import { toastApiError } from "@/lib/api/toastApiError";

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

/**
 * The post-completion gallery's three actions — upload, delete, download — and
 * the two halves of attendance.
 *
 * Grouped together because they all act on the same record through the same
 * refetch, and none of them touches the registration state machine.
 */
export function useLearnServeMediaActions(
  data: LearnServeDetailsData,
  dialogs: LearnServeDialogs
) {
  const {
    id,
    t,
    selectedLanguage,
    opportunityData,
    refetch,
    updateImagesMutation,
    deleteImageMutation,
    downloadImageMutation,
    issueAttendanceCodeMutation,
  } = data;

  const handleFileUpload = async (files: File[]) => {
    // One upload at a time: a second click on «حفظ» would store the set twice.
    if (updateImagesMutation.isPending) return;
    const currentCount = opportunityData?.after_completed_images_count || 0;
    const maxAllowed = MAX_AFTER_COMPLETED_IMAGES - currentCount;

    if (files.length > maxAllowed) {
      toast.error(t("COMMON.MAX_FILES_EXCEEDED"));
      dialogs.setPendingFiles([]);
      return;
    }

    const formData = new FormData();
    files.forEach((file, index) => {
      // Indices continue from the already-uploaded images
      const adjustedIndex = currentCount + index;
      formData.append(`new_opportunity_images_${adjustedIndex}`, file);
      formData.append(
        `new_opportunity_images_is_after_completed_${adjustedIndex}`,
        "true"
      );
    });

    try {
      await updateImagesMutation.mutateAsync({ id, formData });
      toast.success(t("COMMON.TOAST.OPPORTUNITY_IMAGE_UPLOAD_SUCCESS"));
      dialogs.setPendingFiles([]);
      refetch();
    } catch (error) {
      console.error("Upload failed:", error);
      toastApiError(error, selectedLanguage, t("COMMON.TOAST.OPPORTUNITY_IMAGE_UPLOAD_FAILED"));
    }
  };

  const openDeleteModal = (imageId: number) => {
    dialogs.setDeletingImageId(imageId);
    dialogs.setShowDeleteModal(true);
  };

  const handleConfirmDelete = async () => {
    if (!dialogs.deletingImageId || deleteImageMutation.isPending) return;
    try {
      await deleteImageMutation.mutateAsync({
        image_ids: [dialogs.deletingImageId],
        type: "learnserve",
      });
      toast.success(t("COMMON.TOAST.DELETE_IMAGE_SUCCESS"));
      dialogs.setShowDeleteModal(false);
      dialogs.setDeletingImageId(null);
      refetch();
    } catch (error) {
      // The server says why (e.g. not the organizer, record locked).
      toastApiError(error, selectedLanguage, t("COMMON.TOAST.DELETE_IMAGE_FAILED"));
    }
  };

  const handleDownloadImage = async (
    imageId: number,
    imageName = "opportunity_image"
  ) => {
    if (downloadImageMutation.isPending) return; // one download at a time
    try {
      const { blob, filename } = await downloadImageMutation.mutateAsync({
        image_id: imageId,
        fallbackName: imageName,
      });

      const blobUrl = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = blobUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(blobUrl);

      toast.success(t("COMMON.DOWNLOAD_SUCCESS"));
    } catch (error) {
      console.error("Download error:", error);
      toastApiError(error, selectedLanguage, t("COMMON.DOWNLOAD_FAILURE"));
    }
  };

  const handleIssueAttendanceCode = () => {
    dialogs.setShowAttendanceQr(true);
    issueAttendanceCodeMutation.mutate();
  };

  return {
    handleFileUpload,
    openDeleteModal,
    handleConfirmDelete,
    handleDownloadImage,
    handleIssueAttendanceCode,
  };
}
