"use client";

import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { getApiErrorMessages, getApiErrorMessage, isApiSuccess, isBanRefusal } from "@/lib/api/errors";
import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";
import type { SaveMutation } from "@/features/shared/saveMutation";
import type { ApiResponse } from "@/lib/api/types";
import {
  checkoutFromRegistration,
  goToCheckout,
  isPaidRegistrationResponse,
  type RegistrationResponseRecord,
} from "@/features/opportunities/payment";
import { registerWithConflictCheck } from "@/features/opportunities/scheduleConflict";

/**
 * Booking a consultation slot.
 *
 * On success it stashes the confirmation payload and routes to the thank-you
 * page, so the receipt survives the navigation without a query string —
 * unless the opportunity is **paid**, in which case the same endpoint answers
 * with a checkout to go to instead and the booking is not yet a booking. A
 * consultation can be paid like any other development opportunity: the server
 * branches on `is_paid`, not on the learning type.
 */
export function useConsultationBooking({
  opportunityId,
  opportunityDetails,
  selectedLanguage,
  t,
  onClose,
  registerMutation,
}: {
  opportunityId: string;
  /** Spread into the thank-you payload, so it must be an object. */
  opportunityDetails: object | undefined;
  selectedLanguage: string;
  t: (key: string) => string;
  onClose: () => void;
  /** Only `mutateAsync` is used, with the slot body below. */
  registerMutation: SaveMutation<
    { opportunity_id: string; time_slot_id: number; cancel_conflicting?: true },
    ApiResponse<RegistrationResponseRecord>
  >;
}) {
  const router = useRouter();
  const queryClient = useQueryClient();

  return async (values: { selectedSlotId?: number | null }) => {

    if (!values.selectedSlotId) return;

    try {
      const slotId = values.selectedSlotId;
      const response = await registerWithConflictCheck((extra) =>
        registerMutation.mutateAsync({
          opportunity_id: opportunityId,
          time_slot_id: slotId,
          ...extra,
        })
      );
      // Kept the registration that clashes: nothing to book.
      if (response === null) {
        onClose();
        return;
      }

      if (!isApiSuccess(response)) {
        toast.error(getApiErrorMessage(response, selectedLanguage, t("COMMON.TOAST.TIME_SLOT_REGISTRATION_FAILED")));
        return;
      }

      /* BE-125 — the slot is held, not booked, until the gateway confirms.
         See `features/opportunities/payment.ts`. */
      const checkout = checkoutFromRegistration(response);
      if (checkout) {
        toast.success(t("COMMON.TOAST.REDIRECTING_TO_PAYMENT"));
        onClose();
        goToCheckout(checkout.gateway_checkout_url as string);
        return;
      }

      if (isPaidRegistrationResponse(response)) {
        toast.error(t("COMMON.TOAST.CHECKOUT_UNAVAILABLE"));
        onClose();
        return;
      }

      // A16: free registration sends no email — «تم تسجيلك بنجاح» only. The
      // per-viewer detail is cached; coming back must not offer «تسجيل» again.
      toast.success(t("COMMON.YOU_ARE_REGISTERED"));
      void queryClient.invalidateQueries({ queryKey: ["learn-serve-opportunity", opportunityId] });
      setNavState(NAV_STATE_KEYS.opportunityThankyou, {
        ...opportunityDetails,
        islearnserve: true,
      });
      onClose();
      router.push("/register-now");
    } catch (error) {
      // The ban popup already explains the refusal (PDF p.43).
      if (isBanRefusal(error)) {
        onClose();
        return;
      }
      /*
       * Through the shared helper rather than by reaching into the payload.
       * This handler used to read `errors[key][language]` itself, which covered
       * only the **older** envelope — so the moment this endpoint moves to
       * `response_status.validation_errors` (as most already have) every
       * field-level reason would have collapsed into the generic fallback.
       * `getApiErrorMessages` reads both shapes and makes the same language
       * choice, then falls back to the envelope's `msg`.
       */
      const messages = getApiErrorMessages(error, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.TIME_SLOT_REGISTRATION_FAILED"));
      }
    }
  };
}
