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

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import type { FormikHelpers } from "formik";
import { getApiErrorMessage, getApiErrorMessages } from "@/lib/api/errors";
import { submitRequiredInterests } from "@/features/shared/submitRequiredInterests";
import {
  createVolunteerOpportunity,
  deleteOpportunityImage,
  syncOpportunitySponsors,
  updateVolunteerOpportunity,
} from "@/features/opportunities/services/opportunities";
import { resubmitVolunteerOpportunity } from "@/features/opportunities/services/registrations";
import { buildVolunteerPayload } from "./buildVolunteerPayload";
import {
  runVolunteerCreate,
  runVolunteerUpdate,
  VOLUNTEER_FIELD_ALIASES,
} from "./volunteerSubmitSteps";
import type { VolunteerFormValues } from "./volunteerFormTypes";
import { setPostingOutcome } from "@/lib/navigationState";

/** Everything the save needs from the form that is not in the values. */
export interface VolunteerSubmitContext {
  /** Present when editing or reposting; absent when publishing new. */
  id?: string | null;
  /** A repost creates a new record, copying only selected announcement media. */
  isRepublish?: boolean;
  /** Image ids to keep, and ids to delete once the save succeeds. */
  existingImageIds: number[];
  removedImageIds: number[];
  clearRemovedImages: () => void;
  /** The "about the opportunity" section is not shown for every publisher. */
  showOpportunitySection: boolean;
  /** The accessibility tick-boxes, which ride along in the payload. */
  selectedCheckBoxes: string[];
  /** Cleared alongside the form on a successful publish. */
  setSelectedCheckBoxes: (values: string[]) => void;
  selectedLanguage: string;
  opportunityData?: NonNullable<AuthoringTarget["source"]> & {
    /** A rejected record stays rejected until explicitly resubmitted. */
    approval_status?: string | null;
    opportunity_sponsor_images?: Array<{
      id: string | number;
      organization?: { id?: string | number } | string | number | null;
    }> | null;
  } | null;
  /** Records the created id so the role editor can open against it. */
  setVolunteerOpportunityId: (id: string | null) => void;
  openRoleModal: () => void;
}

/**
 * Saving a volunteering opportunity, start to finish.
 *
 * More than one request: the record, then its sponsor relationships, then the
 * deletion of any images the organizer removed. Publishing also opens the role
 * editor for the new record, which is why the created id is needed here.
 *
 * The *body* of the first request is `buildVolunteerPayload`; this is
 * everything around it.
 */
export function useVolunteerSubmit({
  id,
  isRepublish,
  existingImageIds,
  removedImageIds,
  clearRemovedImages,
  showOpportunitySection,
  selectedCheckBoxes,
  setSelectedCheckBoxes,
  selectedLanguage,
  opportunityData,
  setVolunteerOpportunityId,
  openRoleModal,
}: VolunteerSubmitContext) {
  const { t } = useTranslation();
  const router = useRouter();
  const queryClient = useQueryClient();
  const canWrite = useAuthoringWriteGuard({ id, isRepublish, source: opportunityData });

  const fieldErrorTarget = useRef<{ fields: string[]; setFieldError: FormikHelpers<VolunteerFormValues>["setFieldError"] } | null>(null);
  const [pendingFormData, setPendingFormData] = useState<FormData | null>(null);
  const [pendingSponsorIds, setPendingSponsorIds] = useState<string[]>([]);
  const [showUpdateConfirmModal, setShowUpdateConfirmModal] = useState(false);

  const createOpportunityMutation = useMutation({
    mutationFn: createVolunteerOpportunity,
  });
  const updateOpportunityMutation = useMutation({
    mutationFn: updateVolunteerOpportunity,
  });

  const handleSubmit = async (
    values: VolunteerFormValues,
    { resetForm, setFieldError }: FormikHelpers<VolunteerFormValues>
  ) => {
    if (!canWrite()) return;
    fieldErrorTarget.current = { fields: Object.keys(values), setFieldError };
    try {
      const { formData, sponsorIds } = buildVolunteerPayload({
        values,
        isRepublish,
        id,
        existingImageIds,
        showOpportunitySection,
        selectedLanguage,
        selectedCheckBoxes,
      });

      if (id && !isRepublish) {
        // Show confirmation modal for update
        setPendingFormData(formData);
        setPendingSponsorIds(sponsorIds);
        setShowUpdateConfirmModal(true);
        return; // Keep the edited values available if confirmation is cancelled or fails.
      } else {
        // Create new opportunity, then open the role editor for it
        const outcome = await runVolunteerCreate({
          formData,
          sponsorIds,
          steps: {
            create: async (payload) => {
              const { result, interestsDropped } =
                await submitRequiredInterests(payload, (body) =>
                  createOpportunityMutation.mutateAsync(body)
                );
              const created = result?.data?.id;
              setPostingOutcome(result?.data);
              return {
                interestsDropped,
                opportunityId: created != null ? String(created) : null,
              };
            },
            syncSponsors: (opportunityId, organizationIds) =>
              syncOpportunitySponsors({
                type: "volunteer",
                opportunityId,
                organizationIds,
              }),
          },
        });
        if (outcome.interestsDropped) {
          toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
        }
        if (outcome.opportunityId != null) {
          setVolunteerOpportunityId(outcome.opportunityId);
          toast.success(t("COMMON.TOAST.CREATE_OPPORTUNITY_SUCCESS"));
          // Created, but the sponsors were refused (e.g. inside 24 h of the start).
          if (outcome.sponsorError !== undefined) {
            toast.error(getApiErrorMessage(outcome.sponsorError, selectedLanguage, t("COMMON.TOAST.UPDATE_OPPORTUNITY_FAILED")));
          }
          openRoleModal();
        }
      }

      resetForm();
      setSelectedCheckBoxes([]);
    } catch (err) {
      const target = fieldErrorTarget.current;
      if (target) applyFormApiErrors(err, selectedLanguage, target.fields, target.setFieldError, VOLUNTEER_FIELD_ALIASES);
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.CREATE_OPPORTUNITY_FAILED"));
      }
    }
  };

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

    // The resubmit's own refusal (e.g. publishing paused) is the reason to show.
    let resubmitError: unknown = null;
    try {
      // A rejected opportunity stays rejected until explicitly resubmitted —
      // editing it alone doesn't move it back into the review queue.
      const outcome = await runVolunteerUpdate({
        formData: pendingFormData,
        removedImageIds,
        sponsorIds: pendingSponsorIds,
        isRejected: opportunityData?.approval_status === "rejected",
        steps: {
          save: async (payload) => {
            const { interestsDropped } = await submitRequiredInterests(
              payload,
              (body) => updateOpportunityMutation.mutateAsync({ id, data: body })
            );
            return { interestsDropped };
          },
          deleteImages: (imageIds) =>
            deleteOpportunityImage({ image_ids: imageIds, type: "volunteer" }),
          syncSponsors: (organizationIds) =>
            syncOpportunitySponsors({
              type: "volunteer",
              opportunityId: id,
              organizationIds,
              currentSponsors: opportunityData?.opportunity_sponsor_images ?? [],
            }),
          resubmit: () => resubmitVolunteerOpportunity(id).catch((error: unknown) => {
            resubmitError = error;
            throw error;
          }),
        },
      });

      if (outcome.interestsDropped) {
        toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
      }
      if (outcome.resubmitted) {
        toast.success(t("COMMON.TOAST.RESUBMIT_SUCCESS"));
      } else if (outcome.resubmitFailed) {
        toast.error(getApiErrorMessage(resubmitError, selectedLanguage, t("COMMON.TOAST.RESUBMIT_FAILED")));
      } else {
        toast.success(t("COMMON.TOAST.UPDATE_OPPORTUNITY_SUCCESS"));
      }

      /* Both caches hold the pre-edit record for the 1-minute stale time: the
         detail page would show the old values, and reopening the form would
         seed it with them — a second save then reverted the first. */
      void queryClient.invalidateQueries({ queryKey: ["volunteer-opportunity", id] });
      void queryClient.invalidateQueries({ queryKey: ["opportunity-details", id] });
      router.push(`/volunteer-event-detail/${id}`);
      setPendingFormData(null);
      setPendingSponsorIds([]);
      clearRemovedImages();
    } catch (err) {
      const target = fieldErrorTarget.current;
      if (target) applyFormApiErrors(err, selectedLanguage, target.fields, target.setFieldError, VOLUNTEER_FIELD_ALIASES);
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.UPDATE_OPPORTUNITY_FAILED"));
      }
      throw err;
    }
  };

  return {
    handleSubmit,
    handleUpdateConfirm,
    pendingFormData,
    setPendingFormData,
    pendingSponsorIds,
    setPendingSponsorIds,
    showUpdateConfirmModal,
    setShowUpdateConfirmModal,
    createOpportunityMutation,
    updateOpportunityMutation,
  };
}
