"use client";

import { useTranslation } from "react-i18next";
import moment from "moment";
import { Modal } from "@/components/ui/Modal";
import { getApiErrorMessage } from "@/lib/api/errors";
import AttendanceQrModal from "@/features/opportunities/components/AttendanceQrModal";
import DeleteOpportunityModal from "@/features/opportunities/components/DeleteOpportunityModal";
import { canEditOrDelete } from "@/features/shared/opportunityButtonState";
import DeletionReviewAction from "./DeletionReviewAction";
import ConfirmActionModal from "./ConfirmActionModal";
import { type LearnServeDetailsData } from "./useLearnServeDetailsData";
import { type LearnServeDialogs } from "./useLearnServeDialogs";
import { type useLearnServeRegistrationActions } from "./useLearnServeRegistrationActions";
import { type useLearnServeMediaActions } from "./useLearnServeMediaActions";
import { developmentAttendanceOpensAt } from "../developmentAttendanceWindow";
import { isLearnServeDeletionPending } from "./learnServeDetailsViewState";

interface LearnServeManageModalsProps {
  data: LearnServeDetailsData;
  dialogs: LearnServeDialogs;
  registration: ReturnType<typeof useLearnServeRegistrationActions>;
  media: ReturnType<typeof useLearnServeMediaActions>;
  isRepostState: boolean;
  actionButtonLabel: string;
  opportunityTitle: string;
}

/**
 * Every dialog behind the creator's icon rail, plus the two attendance sheets.
 *
 * All six are driven by `dialogs`, so they move together: the page renders this
 * once and never mentions a dialog again.
 */
export default function LearnServeManageModals({
  data,
  dialogs,
  registration,
  media,
  isRepostState,
  actionButtonLabel,
  opportunityTitle,
}: LearnServeManageModalsProps) {
  const { t } = useTranslation();
  const {
    id,
    selectedLanguage,
    refetch,
    deleteImageMutation,
    issueAttendanceCodeMutation,
  } = data;

  const issuedCode = issueAttendanceCodeMutation.data?.data;
  const scanOpensAt = developmentAttendanceOpensAt(data.opportunityData);

  return (
    <>
      {data.isCreator && !canEditOrDelete(data.opportunityData) && <div className="mb-6 flex justify-center"><DeletionReviewAction id={String(id)} type="learnserve" started={isRepostState} paidLocked={data.opportunityData?.has_successful_payments || data.opportunityData?.has_active_payments} requestable={data.opportunityData?.can_request_deletion !== false} pending={isLearnServeDeletionPending(data.opportunityData)} onChanged={() => { void refetch(); }} /></div>}
      <ConfirmActionModal
        open={dialogs.showDeleteModal}
        onClose={() => dialogs.setShowDeleteModal(false)}
        title={t("COMMON.DELETE_IMAGE")}
        message={t("COMMON.ARE_YOU_SURE_DELETE_IMAGE")}
        onConfirm={media.handleConfirmDelete}
        isPending={deleteImageMutation.isPending}
      />

      {/* The confirm lives in the shared modal, which owns the reason field and
          the request call — same component the volunteer page uses, with the
          `learnserve` type the deletion endpoint expects. */}
      <Modal
        open={dialogs.showDeleteOpportunity}
        onClose={() => dialogs.setShowDeleteOpportunity(false)}
        title={t("COMMON.DELETE_OPPORTUNITY")}
        size="small"
      >
        <DeleteOpportunityModal
          navigateBackOnDelete
          opportunityId={id}
          type="learnserve"
          setOpenModal={() => dialogs.setShowDeleteOpportunity(false)}
          refetch={() => {
            void refetch();
          }}
        />
      </Modal>

      {/* BE-61 Part B — one sheet, with its expiry printed on it. */}
      <AttendanceQrModal
        open={dialogs.showAttendanceQr}
        onClose={() => dialogs.setShowAttendanceQr(false)}
        title={t("COMMON.ATTENDANCE_QR")}
        instructions={
          scanOpensAt
            ? t("COMMON.ATTENDANCE_QR_LEARN_SERVE_PRINTABLE_INSTRUCTIONS", {
                date: scanOpensAt.clone().locale(selectedLanguage).format("DD MMM YYYY, hh:mm A"),
              })
            : t("COMMON.ATTENDANCE_QR_LEARN_SERVE_INSTRUCTIONS")
        }
        isLoading={issueAttendanceCodeMutation.isPending}
        error={
          issueAttendanceCodeMutation.isError
            ? getApiErrorMessage(
                issueAttendanceCodeMutation.error,
                selectedLanguage
              ) || t("COMMON.TOAST.ATTENDANCE_QR_FAILED")
            : null
        }
        sheets={
          issuedCode
            ? [
                {
                  code: issuedCode.code,
                  label: t("COMMON.ATTENDANCE_QR"),
                  caption: opportunityTitle,
                  // The expiry is printed on the sheet itself. With the date as
                  // well as the time: since BE-119 the sheet can be printed a
                  // day ahead, and "valid until 22:00" alone no longer says
                  // which day.
                  footnote: t("COMMON.QR_VALID_UNTIL", {
                    date: moment(issuedCode.expires_at).utcOffset(180).locale(selectedLanguage).format("DD MMM YYYY, hh:mm A"),
                  }),
                },
              ]
            : []
        }
      />

      {/* Repost only. Editing navigates straight to the form — there is
          nothing to agree to in front of a page change, and the back button
          undoes it. Reposting publishes a second opportunity from this one,
          which is worth a question. */}
      <ConfirmActionModal
        open={dialogs.showPrimaryActionConfirm && isRepostState}
        onClose={() => dialogs.setShowPrimaryActionConfirm(false)}
        title={actionButtonLabel}
        message={t("COMMON.ARE_YOU_SURE_REPOST_OPPORTUNITY")}
        onConfirm={registration.handleConfirmPrimaryAction}
      />
    </>
  );
}
