"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";
import {
  closeVolunteerOpportunityRegistration,
  messageVolunteerRegistrants,
  reopenVolunteerOpportunityRegistration,
  resubmitVolunteerOpportunity,
} from "@/features/opportunities/services/registrations";
import { sendVolunteerOpportunityCertificates } from "@/features/opportunities/services/opportunities";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";

/** Which confirmation is up. One at a time, so one piece of state. */
export type PendingConfirm =
  | "primary"
  | "close"
  | "reopen"
  | "resubmit"
  | "certificates"
  | "message"
  | "delete";

/**
 * Every mutation behind the creator's icon rail, plus which dialog is open.
 *
 * Split out of `CreatorActionBar` so the rail and its six dialogs are both
 * presentation: what each control *does* lives here, in one place, rather than
 * being read out of the JSX.
 */
export function useCreatorActions(
  opportunityId: string,
  isRepostState: boolean,
  onChanged: () => void
) {
  const { t } = useTranslation();
  const router = useRouter();
  const language = useLanguageStore((s) => s.language);
  const [confirm, setConfirm] = useState<PendingConfirm | null>(null);
  const dismiss = () => setConfirm(null);

  const closeMutation = useMutation({
    mutationFn: () => closeVolunteerOpportunityRegistration(opportunityId),
  });
  /* BE-108 — `all: true` rather than a picked list: the rail has no selection
     to carry, and the screen that does have one (the registrations list) can
     grow its own narrower call later against the same endpoint. */
  const messageMutation = useMutation({
    mutationFn: (values: { subject: string; message: string }) =>
      messageVolunteerRegistrants({ opportunityId, all: true, ...values }),
  });
  const reopenMutation = useMutation({
    mutationFn: () => reopenVolunteerOpportunityRegistration(opportunityId),
  });
  const resubmitMutation = useMutation({
    mutationFn: () => resubmitVolunteerOpportunity(opportunityId),
  });
  const certificatesMutation = useMutation({
    mutationFn: () => sendVolunteerOpportunityCertificates(opportunityId),
  });

  /**
   * Run a mutation behind its confirmation. On success the dialog closes and
   * the page refetches; on failure it stays open so the creator can retry.
   */
  const runAndRefresh =
    (
      mutation: { mutateAsync: () => Promise<unknown> },
      successKey: string,
      failureKey: string
    ) =>
    async () => {
      try {
        await mutation.mutateAsync();
        toast.success(t(successKey));
        dismiss();
        onChanged();
      } catch (error) {
        // The server's refusal (window closed, not the owner…) is the reason;
        // the generic key is only the fallback.
        console.error(failureKey, error);
        toast.error(getApiErrorMessage(error, language, t(failureKey)));
      }
    };

  /**
   * Completion already issued certificates to everyone marked attended; this
   * is for attendance recorded afterwards. `certificates_sent: 0` is a normal
   * answer, not a failure.
   */
  const sendCertificates = async () => {
    try {
      const response = await certificatesMutation.mutateAsync();
      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"));
      // A15: `certificates_outdated` clears server-side once sent — re-read it,
      // or the button and its note stayed up as if nothing had been sent.
      onChanged();
    } catch (error) {
      console.error("Send certificates failed:", error);
      toast.error(getApiErrorMessage(error, language, t("COMMON.TOAST.CERTIFICATES_SEND_FAILED")));
    } finally {
      // Closed either way — the toast carries the outcome, and leaving the
      // dialog up invites a second send of the same certificates.
      dismiss();
    }
  };

  /**
   * BE-108 — send the organizer's message to everyone registered.
   *
   * The toast reports the **email** count the API returns, and says so: every
   * registrant also gets an in-app notification, but anyone with
   * `do_not_disturb` set or no address on file is skipped for mail, so
   * `sent_count` is routinely lower than the number of people reached.
   * Reporting it as "sent to N volunteers" would be wrong.
   */
  const sendMessage = (values: { subject: string; message: string }) => {
    messageMutation.mutate(values, {
      onSuccess: (response) => {
        dismiss();
        toast.success(
          t("COMMON.TOAST.MESSAGE_SENT", {
            count: response?.data?.sent_count ?? 0,
          })
        );
      },
      onError: (error) => {
        /* Same shape as `runAndRefresh` above: log the real reason, show the
           translated one. */
        console.error("COMMON.TOAST.MESSAGE_FAILED", error);
        toast.error(getApiErrorMessage(error, language, t("COMMON.TOAST.MESSAGE_FAILED")));
      },
    });
  };

  /** Edit opens this opportunity; Repost starts a *new* one seeded from it. */
  const openForm = () => {
    dismiss();
    setNavState(
      NAV_STATE_KEYS.volunteerForm,
      isRepostState ? { id: opportunityId, isRepublish: true } : { id: opportunityId }
    );
    router.push("/volunteer-form");
  };

  return {
    confirm,
    setConfirm,
    dismiss,
    closeMutation,
    reopenMutation,
    resubmitMutation,
    certificatesMutation,
    messageMutation,
    sendMessage,
    runAndRefresh,
    sendCertificates,
    openForm,
  };
}

export type CreatorActions = ReturnType<typeof useCreatorActions>;
