"use client";

import { Formik, Form } from "formik";
import { useTranslation } from "react-i18next";

import IndividualSignupExtras from "./IndividualSignupExtras";
import OptionalSignupInterests from "./OptionalSignupInterests";
import IndividualHealthField from "./IndividualHealthField";
import Input from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import SelectInput from "@/components/ui/SelectInput";
import BirthDateField from "@/components/ui/BirthDateField";
import { MIN_SIGNUP_AGE, maxDateOfBirthFor } from "@/features/shared/schemas";
import { cn } from "@/lib/helpers";
import { isUnderageToday } from "@/lib/age";
import { useVolunteerMandate } from "./useVolunteerMandate";
import MandateIdentityFields from "./MandateIdentityFields";
import MandateContactFields from "./MandateContactFields";
import MandateGuardianFields from "./MandateGuardianFields";
import MandateTermsCheckbox from "./MandateTermsCheckbox";
import type { MandatePrefillUser } from "./volunteerMandateParts";

export interface VolunteerMandateDetailsProps {
  /* Nullable as well as optional: the host modal holds `null` until the
     social sign-up hands a record over. */
  userData?: MandatePrefillUser | null;
  onClose?: () => void;
  isModal?: boolean;
}

export default function VolunteerMandateDetails({
  userData: propUserData,
  onClose,
  isModal,
}: VolunteerMandateDetailsProps) {
  const { t } = useTranslation();
  const {
    genderError,
    genderLoading,
    passSocialInfoMutation,
    nicknameAvailability,
    relationshipLoading,
    genderOptions,
    relationshipOptions,
    initialValues,
    validationSchema,
    checkNicknameAvailability,
    handleSubmit,
  } = useVolunteerMandate({
    userData: propUserData,
    onClose,
  });

  if (genderError) {
    return <div>{t("COMMON.ERROR.LOADING_GENDER_OPTIONS")}</div>;
  }

  return (
    <div className={cn(!onClose && "border-t", "border-[#000]")}>
      <div
        className={
          isModal
            ? ""
            : "2xl:py-[40px] laptopmain:py-[50px] laptop:py-[40px] lg:py-[40px] py-[40px]"
        }
      >
        {!isModal && (
          <h2 className="2xl:pb-11 lg:pb-5 pb-5 text-center font-bold xs:text-[22px] xs:leading-[26px] text-[28px] leading-[48px] md:text-[32px] md:leading-[52px] lg:text-[30px] lg:leading-[60px] 2xl:text-[50px] xl:leading-[68.09px] tracking-[0px] text-[#29246D]">
            {t("COMMON.COMPLETEYOURDETAILS")}
          </h2>
        )}
        <Formik
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={handleSubmit}
          enableReinitialize
        >
          {({ setFieldValue, values, errors, touched }) => {
            const isUnder18 = isUnderageToday(values.dob);

            return (
              <div className="flex justify-center">
                <div className="w-[90%] 2xl:w-[720px] lg:w-[720px] md:w-[90%] rounded-lg bg-white">
                  <Form>
                    <div className="flex gap-6 mobilescreen:block">
                      <Input
                        name="first_name"
                        type="text"
                        label={t("COMMON.FIRSTNAMEPLACEHOLDER")}
                        className="text-primary-5"
                        autoComplete="off"
                      />
                      <Input
                        name="last_name"
                        type="text"
                        label={t("COMMON.LASTNAMEPLACEHOLDER")}
                      />
                    </div>
                    <MandateContactFields
                      values={values}
                      setFieldValue={setFieldValue}
                      errors={errors}
                      nicknameAvailability={nicknameAvailability}
                      checkNicknameAvailability={checkNicknameAvailability}
                    />
                    <div className="grid grid-cols-2 mobilescreen:grid-cols-1 mobilescreen:gap-0 gap-5 selectfiled">
                      <BirthDateField
                        name="dob"
                        label={t("COMMON.DATE_OF_BIRTH")}
                        maxDate={maxDateOfBirthFor(MIN_SIGNUP_AGE)}
                      />
                      <SelectInput
                        name="gender"
                        label={t("COMMON.GENDERPLACEHOLDER")}
                        options={genderOptions}
                        onChange={(selectedOption) =>
                          setFieldValue("gender", selectedOption?.value || "")
                        }
                        disabled={genderLoading}
                      />
                    </div>

                    <IndividualHealthField />
                <OptionalSignupInterests />
                <IndividualSignupExtras />
                    <MandateIdentityFields
                      values={values}
                      setFieldValue={setFieldValue}
                    />

                    {/* Emergency Contact Fields - Only shown if user is under 18 */}
                    {isUnder18 && (
                      <>
                        <div className="mt-6 mb-4">
                          <h3 className="text-lg font-semibold text-primary-5">
                            {t("COMMON.EMERGENCY_CONTACT_DETAILS")}
                          </h3>
                          <p className="text-sm text-gray-600 mt-1">
                            {t("COMMON.EMERGENCY_CONTACT_REQUIRED_UNDER_18")}
                          </p>
                        </div>

                        <div className="grid grid-cols-2 mobilescreen:grid-cols-1 mobilescreen:gap-0 gap-6">
                          <Input
                            name="emergency_contact_name"
                            type="text"
                            label={t("COMMON.EMERGENCY_CONTACT_NAME")}
                            lettersOnly
                          />

                          <SelectInput
                            name="emergency_contact_relationship"
                            label={t("COMMON.EMERGENCY_CONTACT_RELATIONSHIP")}
                            options={relationshipOptions}
                            onChange={(selectedOption) =>
                              setFieldValue(
                                "emergency_contact_relationship",
                                selectedOption?.value || "",
                              )
                            }
                            disabled={relationshipLoading}
                          />
                        </div>

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

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

                    <Button
                      className="mx-auto mt-[25px]"
                      variant="primary"
                      size="medium"
                      type="submit"
                      disabled={
                        passSocialInfoMutation.isPending ||
                        genderLoading ||
                        relationshipLoading
                      }
                      loading={passSocialInfoMutation.isPending}
                    >
                      {t("COMMON.SUBMIT")}
                    </Button>
                  </Form>
                </div>
              </div>
            );
          }}
        </Formik>
      </div>
    </div>
  );
}
