"use client";
import { useAuthoringWriteGuard } from "@/features/shared/useAuthoringWriteGuard";
import type { AuthoringTarget } from "@/features/shared/authoringAccess";
import { applyFormApiErrors } from "@/features/shared/formApiErrors";

import { useRouter } from "next/navigation";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { FormikHelpers } from "formik";
import { getApiErrorMessage, getApiErrorMessages, isApiSuccess } from "@/lib/api/errors";
import { submitRequiredInterests } from "@/features/shared/submitRequiredInterests";
import { deleteOpportunityImage, syncOpportunitySponsors } from "@/features/opportunities/services/opportunities";
import { createLearnServeOpportunity, updateLearnServeOpportunity } from "@/features/opportunities/services/learnServe";
import { deleteAllTimeSlots } from "@/features/opportunities/services/registrations";
import { updateOrganizerProfile } from "@/features/profile/services/profileApi";
import { normalizeIban } from "@/features/trainer/trainerRequest";
import { PublishPermissions } from "@/lib/publishPermissions";
import { buildLearnServePayload } from "./buildLearnServePayload";
import { LearnServeFormValues } from "./learnServeFormTypes";
import { setPostingOutcome } from "@/lib/navigationState";

/** The form values held back while an "are you sure?" dialog is up. */
/** sessionStorage keys for an in-progress create, so timings survive a reload. */
const OPPORTUNITY_ID_KEY = "learnServe_opportunityId";
const OPPORTUNITY_DETAILS_KEY = "learnServe_opportunityDetails";

export interface PendingSubmission {
  values: LearnServeFormValues;
  helpers: FormikHelpers<LearnServeFormValues>;
}

/**
 * Saving a development opportunity, start to finish.
 *
 * More than one request: the record itself, then the sponsor relationships,
 * then the deletion of any images the organizer removed — and, on an edit whose
 * schedule changed, the old time slots first. Which of those run, and in what
 * order, is the whole of this hook. The *body* of the first request is
 * `buildLearnServePayload`; this is everything around it.
 */
/**
 * Everything the save needs from the form that is not in the values.
 *
 * Passed as one object rather than twenty parameters: these are all facts about
 * *this* opportunity and *this* publisher, and a positional list of that length
 * is a standing invitation to transpose two of them.
 */
export interface LearnServeSubmitContext {
  /** Present when editing or reposting; absent when publishing new. */
  id?: string | null;
  /** A repost creates a new record seeded from `id`, sharing no media. */
  isRepublish?: boolean;
  publishPermissions: PublishPermissions;

  internshipTypeId?: string;
  courseTypeId?: string;
  onlineFormatId?: string;

  /** Image ids to keep, and ids to delete once the save succeeds. */
  existingImageIds: number[];
  removedImageIds: number[];
  clearRemovedImages: () => void;

  /** The opportunity being edited, for the title shown in confirmations. */
  opportunityData?: NonNullable<AuthoringTarget["source"]> & {
    title_en?: string | null;
    title_ar?: string | null;
    /** Existing sponsor relations, so the sync knows what to remove. */
    opportunity_sponsor_images?: Array<{
      id: string | number;
      organization?: { id?: string | number } | string | number | null;
    }> | null;
  } | null;

  /** Records the newly created record's id, once the create call returns. */
  setOpportunityId: (id: number | null) => void;
  setOpportunityDetails: (details: {
    startDate: string;
    endDate: string;
    startTime: string;
    endTime: string;
  }) => void;

  /** Held-back values while a confirmation dialog is up. */
  pendingFormData: PendingSubmission | null;
  setPendingFormData: (pending: PendingSubmission | null) => void;
  setConfirmModalOpen: (open: boolean) => void;
  setShowUpdateConfirmModal: (open: boolean) => void;

  selectedLanguage: string;
}

export function useLearnServeSubmit({
  id,
  isRepublish,
  publishPermissions,
  internshipTypeId,
  courseTypeId,
  onlineFormatId,
  existingImageIds,
  removedImageIds,
  clearRemovedImages,
  opportunityData,
  setOpportunityId,
  setOpportunityDetails,
  pendingFormData,
  setPendingFormData,
  setConfirmModalOpen,
  setShowUpdateConfirmModal,
  selectedLanguage,
}: LearnServeSubmitContext) {
  const { t } = useTranslation();
  const router = useRouter();
  const canWrite = useAuthoringWriteGuard({ id, isRepublish, source: opportunityData });
  const queryClient = useQueryClient();

  const createOpportunityMutation = useMutation({
    mutationFn: createLearnServeOpportunity,
  });
  const updateOpportunityMutation = useMutation({
    mutationFn: updateLearnServeOpportunity,
  });
  const deleteTimeSlotsMutation = useMutation({ mutationFn: deleteAllTimeSlots });

  const reportSubmitError = (error: unknown, isUpdate: boolean) => {
    const messages = getApiErrorMessages(error, selectedLanguage);
    if (messages.length > 0) {
      messages.forEach((message) => toast.error(message));
    } else {
      toast.error(
        isUpdate && !isRepublish
          ? t("COMMON.TOAST.UPDATE_OPPORTUNITY_FAILED")
          : t("COMMON.TOAST.CREATE_OPPORTUNITY_FAILED")
      );
    }
  };

  const proceedWithSubmission = async (
    values: LearnServeFormValues,
    helpers: FormikHelpers<LearnServeFormValues>,
    isUpdate: boolean
  ) => {
    if (!canWrite()) return;
    try {

      if (values.is_paid === "true" && values.payout_bank_needed && !values.payout_bank_edit) {
        const bankResponse = await updateOrganizerProfile({
          bank_id: values.payout_bank_id || undefined,
          bank_name: values.payout_bank_name.trim(),
          bank_account_holder_name: values.payout_bank_holder.trim(),
          bank_account_number: normalizeIban(values.payout_iban),
        });
        if (!isApiSuccess(bankResponse)) throw bankResponse;
        await queryClient.invalidateQueries({ queryKey: ["organizer-profile"] });
      }

      const {
        formData,
        formattedStartDate,
        formattedEndDate,
        formattedStartTime,
        formattedEndTime,
        sponsorIds,
      } = buildLearnServePayload({
        values,
        isUpdate,
        isRepublish,
        id,
        existingImageIds,
        publishPermissions,
        internshipTypeId,
        courseTypeId,
        onlineFormatId,
      });

      if (isUpdate && id && !isRepublish) {
        const { interestsDropped } = await submitRequiredInterests(
          formData,
          (payload: FormData) =>
            updateOpportunityMutation.mutateAsync({ id, data: payload })
        );
        if (interestsDropped) {
          toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
        }
        if (removedImageIds.length > 0) {
          await deleteOpportunityImage({
            image_ids: removedImageIds,
            type: "learnserve",
          });
        }
        await syncOpportunitySponsors({
          type: "learn-serve",
          opportunityId: id,
          organizationIds: sponsorIds,
          currentSponsors: opportunityData?.opportunity_sponsor_images ?? [],
        });
        toast.success(t("COMMON.TOAST.UPDATE_OPPORTUNITY_SUCCESS"));
        clearRemovedImages();
        // The detail page and this form are cached for a minute; without this
        // the organizer lands on the pre-edit record.
        await Promise.all([
          queryClient.invalidateQueries({ queryKey: ["learn-serve-opportunity", String(id)] }),
          queryClient.invalidateQueries({ queryKey: ["learn-serve-opportunity-form", id] }),
        ]);
        router.push(`/learn-share-event-detail/${id}`);
        return;
      }

      const { result: response, interestsDropped } =
        await submitRequiredInterests(formData, (payload: FormData) =>
          createOpportunityMutation.mutateAsync(payload)
        );
      if (interestsDropped) {
        toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
      }
      setPostingOutcome(response?.data);
      if (response?.data?.id) {
        await syncOpportunitySponsors({
          type: "learn-serve",
          opportunityId: String(response.data.id),
          organizationIds: sponsorIds,
        });
        setOpportunityId(response.data.id);
        toast.success(t("COMMON.TOAST.CREATE_OPPURTUNITY_SUCCESS"));

        setOpportunityDetails({
          startDate: formattedStartDate,
          endDate: formattedEndDate,
          startTime: formattedStartTime,
          endTime: formattedEndTime,
        });

        helpers.resetForm();
        // The flow is finished, so the resume breadcrumbs can go
        localStorage.removeItem(OPPORTUNITY_ID_KEY);
        localStorage.removeItem(OPPORTUNITY_DETAILS_KEY);
        router.replace("/posting-thankyou");
      }
    } catch (error) {
      applyFormApiErrors(error, selectedLanguage, Object.keys(values), helpers.setFieldError, { link: "meetingLink", bank_id: "payout_bank_id", bank_name: "payout_bank_name", bank_account_holder_name: "payout_bank_holder", bank_account_number: "payout_iban" });
      reportSubmitError(error, isUpdate);
      throw error; // Re-thrown so the modal handlers can keep themselves open
    }
  };

  const handleSubmit = async (
    values: LearnServeFormValues,
    helpers: FormikHelpers<LearnServeFormValues>
  ) => {
    try {
      // Reposting always creates a new opportunity, even though `id` is set
      await proceedWithSubmission(values, helpers, !!id && !isRepublish);
    } catch {
      // Already surfaced in proceedWithSubmission
    }
  };

  const handleConfirmDeleteTimeSlots = async () => {
    if (!pendingFormData || !id || isRepublish || !canWrite()) return;

    try {
      await deleteTimeSlotsMutation.mutateAsync(Number(id));
      toast.success(t("COMMON.TOAST.DELETE_TIMESLOTS_SUCCESS"));

      const { values, helpers } = pendingFormData;
      await proceedWithSubmission(values, helpers, true);

      setConfirmModalOpen(false);
      setPendingFormData(null);
    } catch (error) {
      toast.error(
        getApiErrorMessage(
          error,
          selectedLanguage,
          t("COMMON.TOAST.DELETE_TIMESLOTS_FAILED")
        )
      );
      // Leave the modal open so the user can retry or cancel
    }
  };

  const handleCancelDeleteTimeSlots = () => {
    setConfirmModalOpen(false);
    setPendingFormData(null);
  };

  const handleUpdateConfirm = async () => {
    if (!pendingFormData) return;

    try {
      const { values, helpers } = pendingFormData;
      await proceedWithSubmission(values, helpers, true);

      setShowUpdateConfirmModal(false);
      setPendingFormData(null);
    } catch (error) {
      console.error("Error in handleUpdateConfirm:", error);
      // Leave the modal open so the user can retry or cancel
    }
  };


  return {
    createOpportunityMutation,
    updateOpportunityMutation,
    handleSubmit,
    handleConfirmDeleteTimeSlots,
    handleCancelDeleteTimeSlots,
    handleUpdateConfirm,
  };
}
