"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Modal } from "@/components/ui/Modal";
import VolunteerMandateDetails from "@/features/auth/components/VolunteerMandateDetails";
import AuthRecoveryModals from "../AuthRecoveryModals";
import RegistrationStepModal from "./RegistrationStepModal";
import { type RegistrationStep } from "./registrationStep";
export { type RegistrationStep } from "./registrationStep";
import { type OpportunityRegistrationDetails } from "../VolunteerRegisterRoleModal";
import type { OtpType } from "@/features/auth/services/authApi";
import type { MandatePrefillUser } from "@/features/auth/components/volunteerMandateParts";

interface RegistrationFlowModalsProps {
  /** The open step, or null when the flow is closed. */
  step: RegistrationStep | null;
  onStepChange: (step: RegistrationStep | null) => void;
  opportunityId: string;
  organizationId?: string;
  opportunityDetails: OpportunityRegistrationDetails;
  refetch: () => void;
}

/**
 * Everything between "Register" and a registration: sign in, sign up, email
 * verification, forgot / reset password, profile completion, the role picker
 * and the two confirmations.
 *
 * The page only decides *where the flow starts* — which step `step` opens on.
 * Every hop after that (login → sign-up, login → forgot password, verification
 * → reset → back to login) happens in here, which is why the five secondary
 * dialogs and their state live here too rather than on the page.
 */
export default function RegistrationFlowModals({
  step,
  onStepChange,
  opportunityId,
  organizationId,
  opportunityDetails,
  refetch,
}: RegistrationFlowModalsProps) {
  const { t } = useTranslation();

  /** The role picker's form reports its own submit state to the footer button. */
  const [isSubmittingRoles, setIsSubmittingRoles] = useState(false);

  const [verification, setVerification] = useState<{
    email: string;
    otpType: OtpType;
  } | null>(null);
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const [resetPassword, setResetPassword] = useState<{
    email: string;
    token: string;
  } | null>(null);
  /* The mandate dialog opens when a sign-up form calls `setMandateUser`
     through `RegistrationStepModal`; closing it clears the user. (The LinkedIn
     hand-off that used to open it from a stash was removed with LinkedIn
     sign-in — client answers p.6, item 19.) */
  const [mandateUser, setMandateUser] = useState<MandatePrefillUser | null>(
    null
  );

  const closeMandate = () => setMandateUser(null);

  const close = () => onStepChange(null);

  const showEmailVerification = (email: string, otpType: OtpType) =>
    setVerification({ email, otpType });

  const showLogin = () => onStepChange("login");

  const showForgot = () => {
    setShowForgotPassword(true);
    close();
  };

  const showReset = (email: string, token: string) => {
    setResetPassword({ email, token });
    setVerification(null);
  };

  return (
    <>
      <RegistrationStepModal
        step={step}
        onStepChange={onStepChange}
        close={close}
        opportunityId={opportunityId}
        organizationId={organizationId}
        opportunityDetails={opportunityDetails}
        refetch={refetch}
        isSubmittingRoles={isSubmittingRoles}
        setIsSubmittingRoles={setIsSubmittingRoles}
        showEmailVerification={showEmailVerification}
        showForgot={showForgot}
        setMandateUser={setMandateUser}
      />

      {/*
        The same three detours the development page uses, through the same
        component. This file had its own copy of all three dialogs; the only
        difference was the state shape — one `verification` object here against
        three separate values there — so the object is adapted at the boundary
        rather than either side being rewritten.
      */}
      <AuthRecoveryModals
        showEmailVerification={verification !== null}
        setShowEmailVerification={(open) => {
          if (!open) setVerification(null);
        }}
        verificationEmail={verification?.email ?? ""}
        otpType={verification?.otpType ?? "register"}
        showForgotPassword={showForgotPassword}
        setShowForgotPassword={setShowForgotPassword}
        showResetPassword={resetPassword !== null}
        setShowResetPassword={(open) => {
          if (!open) setResetPassword(null);
        }}
        resetPasswordData={resetPassword}
        onShowLogin={showLogin}
        onShowResetPassword={showReset}
        onShowEmailVerification={showEmailVerification}
      />

      <Modal
        open={mandateUser !== null}
        onClose={closeMandate}
        title={t("COMMON.COMPLETEYOURDETAILS")}
        size="md"
      >
        <VolunteerMandateDetails
          userData={mandateUser ?? undefined}
          onClose={closeMandate}
          isModal
        />
      </Modal>
    </>
  );
}
