"use client";

import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { deleteLearnServeRegistrationByOpportunity } from "@/features/opportunities/services/learnServe";
import { getApiErrorMessage } from "@/lib/api/errors";

/**
 * Removing one registration, with its confirmation.
 *
 * Its own hook because a delete is the only action here that invalidates the
 * whole paged list — the row numbers shift — so it resets to page one rather
 * than patching the accumulated array the way marking attendance does.
 */
export function useRegistrationRemoval({
  opportunityId,
  t,
  selectedLanguage,
  resetList,
  refetchRegistrations,
}: {
  opportunityId: string | undefined;
  t: (key: string, options?: Record<string, unknown>) => string;
  selectedLanguage: string;
  resetList: () => void;
  refetchRegistrations: () => Promise<unknown>;
}) {
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingRegistrationId, setDeletingRegistrationId] = useState<
    string | null
  >(null);
  const [deletingUserName, setDeletingUserName] = useState("");
  const [deletingHasHistory, setDeletingHasHistory] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const deleteRegistrationMutation = useMutation({
    mutationFn: deleteLearnServeRegistrationByOpportunity,
  });

  const handleDeleteRegistration = async () => {
    if (!opportunityId || !deletingRegistrationId) return;

    try {
      setIsDeleting(true);
      await deleteRegistrationMutation.mutateAsync({
        opportunity_id: opportunityId,
        user_id: deletingRegistrationId,
        // The dialog the organizer just confirmed is the opt-in (BE-138).
        confirm: true,
      });

      setShowDeleteModal(false);
      toast.success(t("COMMON.REGISTRATION_DELETED_SUCCESS"));
      // Reset pagination and user list to force fresh fetch
      resetList();
      await refetchRegistrations();
    } catch (error) {
      console.error("Error deleting registration:", error);
      // The API answers `{ msg, response_status }`; the old
      // `message_en` / `message_ar` read never matched, so a refusal such as
      // "refund them first" (422) failed silently.
      toast.error(
        getApiErrorMessage(error, selectedLanguage, t("COMMON.REGISTRATION_DELETED_FAILED"))
      );
    } finally {
      setIsDeleting(false);
      setDeletingRegistrationId(null);
      setDeletingUserName("");
      setDeletingHasHistory(false);
    }
  };

  return {
    isDeleting,
    showDeleteModal,
    setShowDeleteModal,
    deletingUserName,
    /** The participant attended or holds a certificate — the dialog says so. */
    deletingHasHistory,
    handleDeleteRegistration,
    /** Opens the confirmation; the caller gates it on the attendance deadline. */
    openDeleteModal: (userId: string | number, userName: string, hasHistory = false) => {
      setDeletingRegistrationId(userId.toString());
      setDeletingUserName(userName);
      setDeletingHasHistory(hasHistory);
      setShowDeleteModal(true);
    },
  };
}
