"use client";

import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  downloadLearnServeRegistrations,
  updateLearnServeAttendance,
} from "@/features/opportunities/services/learnServe";
import { sendLearnServeOpportunityCertificates } from "@/features/opportunities/services/opportunities";
import { skippedFromSelection } from "@/features/opportunities/services/learnServe";
import { EMPTY_SELECTION } from "./registrationSelection";
import { type RegisteredUser } from "./learnServeRegisterListTypes";
import { useRegistrationRemoval } from "./useRegistrationRemoval";
import { toastApiError } from "@/lib/api/toastApiError";
import { isApiSuccess } from "@/lib/api/errors";

interface ActionsContext {
  opportunityId: string | undefined;
  t: (key: string, options?: Record<string, unknown>) => string;
  selectedLanguage: string;
  debouncedSearch: string;
  selectedUsers: string[];
  clearSelection: () => void;
  setSelection: (next: typeof EMPTY_SELECTION) => void;
  setAllRegisteredUsers: (
    update: (previous: RegisteredUser[]) => RegisteredUser[]
  ) => void;
  resetList: () => void;
  refetchRegistrations: () => Promise<unknown>;
  /** Null when the type grants no certificate at all; a key when it is too early. */
  sendBlockedReason: string | null | undefined;
  canMarkAttendance: boolean;
  canSendCertificates: boolean;
}

/**
 * The four things the organizer can do from this screen: mark attendance, export
 * the sheet, remove a registration, and send the certificates.
 */
export function useLearnServeRegisterListActions({
  opportunityId,
  t,
  selectedLanguage,
  debouncedSearch,
  selectedUsers,
  clearSelection,
  setAllRegisteredUsers,
  resetList,
  refetchRegistrations,
  sendBlockedReason,
  canMarkAttendance,
  canSendCertificates,
}: ActionsContext) {
  const [isUpdating, setIsUpdating] = useState(false);
  const downloadMutation = useMutation({
    mutationFn: downloadLearnServeRegistrations,
  });
  const updateAttendanceMutation = useMutation({
    mutationFn: updateLearnServeAttendance,
  });
  const sendCertificatesMutation = useMutation({
    mutationFn: () => sendLearnServeOpportunityCertificates(opportunityId || ""),
  });

  const handleSendCertificates = async () => {
    if (!opportunityId || sendBlockedReason || !canSendCertificates) return;
    try {
      const response = await sendCertificatesMutation.mutateAsync();
      // `certificates_sent: 0` is a normal answer, not a failure: nobody new
      // became eligible. Same wording as the volunteer list, deliberately.
      const sent = response?.data?.certificates_sent ?? 0;
      if (sent > 0) {
        toast.success(t("COMMON.TOAST.CERTIFICATES_SENT", { count: sent }));
      } else {
        toast.info(t("COMMON.TOAST.NO_CERTIFICATES_TO_SEND"));
      }
    } catch (error) {
      console.error("Send learn & serve certificates failed:", error);
      toastApiError(error, selectedLanguage, t("COMMON.TOAST.CERTIFICATES_SEND_FAILED"));
    }
  };

  const handleAttendedClick = async () => {
    if (!canMarkAttendance) return;
    if (selectedUsers.length === 0) {
      toast.error(t("COMMON.SELECT_USERS_TO_MARK"));
      return;
    }

    setIsUpdating(true);
    try {
      const registrationIds = selectedUsers.map((id) => parseInt(id));
      const response = await updateAttendanceMutation.mutateAsync({
        opportunity_id: opportunityId as string,
        data: {
          registration_ids: registrationIds,
          is_attended: true,
        },
      });

      /*
       * `isApiSuccess`, not `response?.status === "success"`. There is no
       * `status` key on the envelope — it is `{ key, msg, code,
       * response_status, data }` — so that half of the check was always
       * false, and the `|| key === "success"` beside it was carrying the
       * whole test. It also missed the case this helper exists for: a
       * rejection sent as HTTP 200 with `key: "success"` but
       * `response_status.error === true`. Surfaced by typing the endpoint.
       */
      if (isApiSuccess(response)) {
        toast.success(t("COMMON.USERS_MARKED_AS_ATTENDED"));
        // A paid course only marks seat holders; the rest are skipped
        // server-side, so the list is re-read instead of flipped locally.
        const skipped = skippedFromSelection(registrationIds.length, response.data?.updated_count);
        if (skipped > 0) {
          toast.info(t("COMMON.ATTENDANCE_SKIPPED_UNPAID", { count: skipped }));
          resetList();
          void refetchRegistrations();
          clearSelection();
          return;
        }

        // Update local state in-place: flip is_attended for the marked rows
        // immediately, without any reset or refetch (avoids loader race conditions).
        const attendedSet = new Set(selectedUsers);
        setAllRegisteredUsers((prev) =>
          prev.map((user) =>
            attendedSet.has(user.id.toString())
              ? { ...user, is_attended: true }
              : user
          )
        );

        clearSelection();
      } else {
        toastApiError(response, selectedLanguage, t("COMMON.FAILED_TO_MARK_ATTENDED"));
      }
    } catch (error) {
      console.error("Failed to mark users as attended:", error);
      // The refusal arrives localized (`msg`), e.g. «يمكن تسجيل الحضور ابتداءً من…».
      toastApiError(error, selectedLanguage, t("COMMON.FAILED_TO_MARK_ATTENDED"));
    } finally {
      setIsUpdating(false);
    }
  };

  const handleDownloadSheet = async () => {
    if (downloadMutation.isPending) return; // one export at a time
    if (!opportunityId) {
      toast.error(t("COMMON.NO_OPPORTUNITY_ID"));
      return;
    }

    try {
      const response = await downloadMutation.mutateAsync({
        opportunity_id: opportunityId,
        search: debouncedSearch,
      });

      if (response.downloadUrl) {
        const link = document.createElement("a");
        link.href = response.downloadUrl;
        link.download = "List of Registered Users.xlsx";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        throw new Error("The API did not return a download URL");
      }
      toast.success(t("COMMON.DOWNLOAD_SUCCESS"));
    } catch (error) {
      console.error("Download failed:", error);
      toastApiError(error, selectedLanguage, t("COMMON.DOWNLOAD_FAILURE"));
    }
  };

  const remove = useRegistrationRemoval({
    opportunityId,
    t,
    selectedLanguage,
    resetList,
    refetchRegistrations,
  });

  return {
    isUpdating,
    sendCertificatesMutation,
    handleSendCertificates,
    handleAttendedClick,
    handleDownloadSheet,
    ...remove,
  };
}
