"use client";

import IndividualSignupExtras from "./IndividualSignupExtras";
import OptionalSignupInterests from "./OptionalSignupInterests";
import IndividualHealthField from "./IndividualHealthField";
import { speaksArabicOptions } from "@/data/Constants";
import { useLanguageStore } from "@/store/languageStore";
import SocialAuthButtons from "./SocialAuthButtons";
import { Form, Formik } from "formik";
import { useTranslation } from "react-i18next";

import BirthDateField from "@/components/ui/BirthDateField";
import { MIN_SIGNUP_AGE, maxDateOfBirthFor } from "@/features/shared/schemas";
import SelectInput from "@/components/ui/SelectInput";
import { DobWatcher, FIELD_LABEL_CLASS } from "./registerVolunteerParts";
import { useRegisterVolunteerModal } from "./useRegisterVolunteerModal";
import RegisterVolunteerContactFields from "./RegisterVolunteerContactFields";
import RegisterVolunteerIdentityFields from "./RegisterVolunteerIdentityFields";
import RegisterVolunteerGuardianFields from "./RegisterVolunteerGuardianFields";
import RegisterVolunteerTerms from "./RegisterVolunteerTerms";
import RegisterVolunteerNameFields from "./RegisterVolunteerNameFields";
import RegisterVolunteerEmergencyFields from "./RegisterVolunteerEmergencyFields";
import RegisterVolunteerEmailFields from "./RegisterVolunteerEmailFields";
import RegisterVolunteerActions from "./RegisterVolunteerActions";
import type { MandatePrefillUser } from "./volunteerMandateParts";
import type { SelfRegisterableUserType } from "@/features/auth/services/authApi";
import type { OtpType } from "@/features/auth/services/authApi";

export interface RegisterVolunteerModalFormProps {
  onClose?: () => void;
  onShowEmailVerification?: (email: string, otpType: OtpType) => void;
  onShowVolunteerMandateDetails?: (userData: MandatePrefillUser) => void;
  /** Comes from the host page; defaults to a volunteer signup. */
  userType?: SelfRegisterableUserType;
}

export default function RegisterVolunteerModalForm(
  props: RegisterVolunteerModalFormProps,
) {
  const { onClose } = props;
  const language = useLanguageStore(s => s.language);
  const { t } = useTranslation();
  const {
    registerMutation,
    isUnder18,
    setIsUnder18,
    nicknameAvailability,
    genderLoading,
    relationshipLoading,
    genderOptions,
    relationshipOptions,
    initialValues,
    validationSchema,
    checkNicknameAvailability,
    handleSubmit,
    googleLogin,
    isBusy,
  } = useRegisterVolunteerModal(props);

  return (
    <div className="relative">
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        {({ setFieldValue, values, errors, touched }) => (
          <div className="mx-auto mobilescreen:w-full">
            <div className="mobilescreen:w-full mx-auto filtermodal">
              <Form>
                <DobWatcher setIsUnder18={setIsUnder18} />

                <RegisterVolunteerNameFields />

                <RegisterVolunteerEmailFields />

                <RegisterVolunteerContactFields
                  values={values}
                  setFieldValue={setFieldValue}
                  errors={errors}
                  nicknameAvailability={nicknameAvailability}
                  checkNicknameAvailability={checkNicknameAvailability}
                />
                <div className="grid grid-cols-2 mobilescreen:gap-[0px] mobilescreen:grid-cols-1 gap-[100px]">
                  <div>
                    <p className={FIELD_LABEL_CLASS}>
                      {t("COMMON.DATE_OF_BIRTH")}
                    </p>
                    <BirthDateField
                      name="dob"
                      label={t("COMMON.DATE_OF_BIRTH")}
                      maxDate={maxDateOfBirthFor(MIN_SIGNUP_AGE)}
                    />
                  </div>
                  <div>
                    <p className={FIELD_LABEL_CLASS}>{t("COMMON.GENDER")}</p>
                    <SelectInput
                      name="gender"
                      label={t("COMMON.GENDERPLACEHOLDER")}
                      options={genderOptions}
                      onChange={(selectedOption) =>
                        setFieldValue("gender", selectedOption?.value || "")
                      }
                      disabled={genderLoading}
                    />
                  </div>
                </div>

                <RegisterVolunteerIdentityFields
                  values={values}
                  setFieldValue={setFieldValue}
                />

                <SelectInput name="speaks_arabic" label={t("COMMON.SPEAKS_ARABIC")} options={speaksArabicOptions.map(o => ({ value: o.value, label: language === "ar" ? o.name_ar : o.name_en }))} />
                <IndividualHealthField />
                <OptionalSignupInterests />
                <IndividualSignupExtras />
                {/* Emergency contact block — only required for under-18 signups */}
                {isUnder18 && (
                  <>
                    <div className="mt-6 mb-4">
                      <h3 className="text-lg font-semibold text-secondary-100">
                        {t("COMMON.EMERGENCY_CONTACT_DETAILS")}
                      </h3>
                      <p className="text-sm text-gray-600 mt-1">
                        {t("COMMON.EMERGENCY_CONTACT_REQUIRED_UNDER_18")}
                      </p>
                    </div>

                    <RegisterVolunteerEmergencyFields
                      setFieldValue={setFieldValue}
                      relationshipOptions={relationshipOptions}
                      relationshipLoading={relationshipLoading}
                    />

                    <RegisterVolunteerGuardianFields
                      values={values}
                      setFieldValue={setFieldValue}
                    />
                  </>
                )}

                <RegisterVolunteerTerms
                  values={values}
                  setFieldValue={setFieldValue}
                  errors={errors}
                  touched={touched}
                />

                <RegisterVolunteerActions
                  isBusy={isBusy}
                  onClose={onClose}
                  registerMutation={registerMutation}
                />
              </Form>
            </div>

            <div>
              <p className="font-semibold text-[18px] xss:text-base leading-[24.51px] pt-8 pb-4 text-primary-5 flex items-center w-full before:flex-1 before:border-t before:border-primary-5 before:mr-4 after:flex-1 after:border-t after:border-primary-5 after:ml-4 rtl:gap-[20px]">
                {t("COMMON.OR.BY")}
              </p>
            </div>
            <SocialAuthButtons
              onGoogle={googleLogin}
            />
          </div>
        )}
      </Formik>
    </div>
  );
}
