"use client";
import { individualSignupExtrasRules, individualSignupExtrasPayload } from "./individualSignupExtrasRules";
import { applyFormApiErrors } from "@/features/shared/formApiErrors";

import { useCallback, useEffect, useRef, useState } from "react";
import { FormikHelpers } from "formik";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as Yup from "yup";
import {
  checkUserRequest,
  readUsernameAvailability,
  usernameAvailabilityQuery,
  getDropdownChoicesRequest,
  passSocialInfoRequest,
  registerRequest,
} from "@/features/auth/services/authApi";
import {
  findNationalityResidency,
  nationalityNeedsPassport,
} from "@/data/Constants";
import { getApiErrorMessages } from "@/lib/api/errors";
import type { SocialProfile } from "@/lib/auth/socialSignup";
import { YupCivilId, YupEmail, YupRequiredString, YupStringMaxLength, YupStrongPassword, createPhoneNumberSchema, YupDateOfBirth, MIN_SIGNUP_AGE } from "@/features/shared/schemas";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { isUnderageToday } from "@/lib/age";

import { type RegisterVolunteerModalFormProps } from "./RegisterVolunteerModalForm";
import { type ChoiceItem } from "./registerVolunteerParts";
import { registerVolunteerInitialValues } from "./registerVolunteerValues";
import {
  EMPTY_NICKNAME_AVAILABILITY,
  type NicknameAvailability,
  USERNAME_PATTERN,
} from "@/features/shared/nicknameAvailability";
import { logRequestError } from "@/lib/api/logError";
import {
  whenValue,
  type YupWhenValue,
} from "@/features/shared/formRules";
import { emergencyContactPayload } from "@/features/auth/emergencyContact";

/**
 * Volunteer sign-up in a modal: the form's values, the dropdown lookups, the
 * under-18 branch, and the register / Google / LinkedIn paths.
 */
export function useRegisterVolunteerModal(
  props: RegisterVolunteerModalFormProps
) {
  const { onClose, onShowEmailVerification, onShowVolunteerMandateDetails, userType = "volunteer" } = props;
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const setUser = useAuthStore((s) => s.setUser);

  const [isUnder18, setIsUnder18] = useState(false);
  const [nicknameAvailability, setNicknameAvailability] = useState<NicknameAvailability>(
    EMPTY_NICKNAME_AVAILABILITY
  );
  const nicknameCheckTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
    null
  );

  const registerMutation = useMutation({ mutationFn: registerRequest });
  const checkUserMutation = useMutation({ mutationFn: checkUserRequest });
  /*
   * `mutateAsync` hoisted out of the mutation object on purpose.
   *
   * React Query keeps this function referentially stable while the mutation
   * object changes identity on every status transition. Depending on the object
   * would rebuild the debounced callback below mid-keystroke and reset its wait;
   * depending on the hoisted function is both stable and complete, so the
   * dependency list is honest rather than suppressed. This replaces an
   * `eslint-disable-next-line react-hooks/exhaustive-deps` whose only missing
   * dependency was `checkUserMutation` — verified by removing the directive and
   * reading what the rule actually reported.
   */
  const checkUserAsync = checkUserMutation.mutateAsync;
  const passSocialInfoMutation = useMutation({
    mutationFn: passSocialInfoRequest,
  });

  const { data: genderData, isLoading: genderLoading } = useQuery({
    queryKey: ["gender-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("gender"),
    enabled: !!selectedLanguage,
  });

  const { data: relationshipData, isLoading: relationshipLoading } = useQuery({
    queryKey: ["emergency-contact-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("emergency_contact_relationship"),
    enabled: !!selectedLanguage,
  });

  const genderOptions =
    genderData?.data?.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: item.id,
    })) || [];

  const relationshipOptions =
    relationshipData?.data?.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: item.id,
    })) || [];

  const initialValues = registerVolunteerInitialValues;

  const requiredWhenUnder18 = <T extends Yup.AnySchema>(schema: () => T) =>
    Yup.string().when("dob", {
      is: isUnderageToday,
      then: schema,
      otherwise: () => Yup.string().notRequired(),
    });

  const validationSchema = Yup.object({
    ...individualSignupExtrasRules(),
    first_name: YupStringMaxLength(100)
      .concat(YupRequiredString),
    last_name: YupStringMaxLength(100)
      .concat(YupRequiredString),
    nickname: YupStringMaxLength(100)
      .concat(YupRequiredString)
      .matches(USERNAME_PATTERN, t("COMMON.USERNAME_FORMAT"))
      .test("nickname-availability", t("COMMON.USERNAME_TAKEN"), function () {
        return nicknameAvailability.available !== false;
      }),
    gender: Yup.string().concat(YupRequiredString),
    phone_number: Yup.string().when(
      "country_code",
      (country_code: YupWhenValue) =>
        createPhoneNumberSchema(whenValue(country_code))
    ),
    country_code: Yup.string().concat(YupRequiredString),
    dob: YupDateOfBirth(MIN_SIGNUP_AGE),
    // Same rule the API applies: civil ID for a Kuwaiti or a resident,
    // passport number for a non-Kuwaiti non-resident.
    civil_id: Yup.string().when("nationality", {
      is: (value: string) => !!value && !nationalityNeedsPassport(value),
      then: () => YupCivilId,
      otherwise: () => Yup.string().notRequired(),
    }),
    passport_number: Yup.string().when("nationality", {
      is: (value: string) => nationalityNeedsPassport(value),
      then: () => YupStringMaxLength(20).concat(YupRequiredString),
      otherwise: () => Yup.string().notRequired(),
    }),
    nationality: Yup.string().concat(YupRequiredString),
    speaks_arabic: Yup.string().oneOf(["true", "false"]).required(t("COMMON.REQUIRED.FIELD")),
    health_concerns: Yup.string().oneOf(["yes", "no"]).required(t("COMMON.REQUIRED.FIELD")),
    email: YupEmail,
    password: YupStrongPassword,
    termsAccepted: Yup.boolean()
      .required(t("COMMON.REQUIRED.FIELD"))
      .oneOf([true], t("COMMON.TERMS_ACCEPTANCE_REQUIRED")),
    emergency_contact_name: requiredWhenUnder18(() =>
      YupStringMaxLength(100).concat(YupRequiredString)
    ),
    emergency_contact_country_code: requiredWhenUnder18(() => YupRequiredString),
    emergency_contact_phone: requiredWhenUnder18(() =>
      Yup.string().when(
        "emergency_contact_country_code",
        /* `unknown[]`, not `any`: Yup 1.x types a `ConditionBuilder`'s first
           argument `any[]` and always passes an array, even for a single key
           — so the `Array.isArray` guard this replaced was dead. The dial
           code is narrowed to a string because `createPhoneNumberSchema`
           takes `string | undefined`. */
        (values: unknown[]) => {
          const code = typeof values[0] === "string" ? values[0] : undefined;
          return createPhoneNumberSchema(code);
        }
      )
    ),
    emergency_contact_civil_id: requiredWhenUnder18(() => YupCivilId),
    emergency_contact_relationship: requiredWhenUnder18(() => YupRequiredString),
  });

  const checkNicknameAvailability = useCallback(
    async (nickname: string) => {
      if (nicknameCheckTimeoutRef.current) {
        clearTimeout(nicknameCheckTimeoutRef.current);
      }

      const nicknameRegex = USERNAME_PATTERN;
      if (!nickname || nickname.trim() === "" || !nicknameRegex.test(nickname.trim())) {
        setNicknameAvailability({
          checking: false,
          available: null,
          message: "",
        });
        return;
      }

      setNicknameAvailability({ checking: true, available: null, message: "" });

      nicknameCheckTimeoutRef.current = setTimeout(async () => {
        try {
          const response = await checkUserAsync(usernameAvailabilityQuery(nickname));
          /* Sign-up enforces `users.username`, so its branch is the answer; an
             older API only answers the `nickname` branch. `null` = not answered. */
          const isAvailable = readUsernameAvailability(response?.data);

          setNicknameAvailability({
            checking: false,
            available: isAvailable,
            message: isAvailable
              ? t("COMMON.USERNAME_AVAILABLE")
              : t("COMMON.USERNAME_TAKEN"),
          });
        } catch (error) {
          logRequestError("Error checking nickname:", error);
          setNicknameAvailability({
            checking: false,
            available: null,
            message: "",
          });
        }
      }, 500);
    },
    [t, checkUserAsync]
  );

  useEffect(() => {
    return () => {
      if (nicknameCheckTimeoutRef.current) {
        clearTimeout(nicknameCheckTimeoutRef.current);
      }
    };
  }, []);

  /* `unknown` — read through `lib/api/errors.ts`, which narrows. */
  const reportRegistrationError = (error: unknown) => {
    const messages = getApiErrorMessages(error, selectedLanguage);
    if (messages.length > 0) {
      messages.forEach((message) => toast.error(message));
    } else {
      toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
    }
  };

  const handleSubmit = async (
    values: typeof initialValues,
    { resetForm, setFieldError }: FormikHelpers<typeof initialValues>
  ) => {
    try {
      const residency = findNationalityResidency(values.nationality);
      const usesPassport = residency?.identifier === "passport_number";

      await registerMutation.mutateAsync({
        ...values,
        ...individualSignupExtrasPayload(values),
        username: values.nickname.trim(),
        /* Blank when the registrant is not a minor. The guardian block only
           renders under 18, but the payload is a spread of the whole Formik bag
           and the dial code now carries a default — so "no guardian" has to be
           said rather than left to the fields never having been written. */
        ...emergencyContactPayload(values, isUnderageToday(values.dob)),
        gender: values.gender,
        country_code: values.country_code,
        phone_number: values.phone_number,
        nationality: residency?.nationality ?? "",
        residency_status: residency?.residency_status ?? "",
        civil_id: usesPassport ? "" : values.civil_id,
        passport_number: usesPassport ? values.passport_number : "",
        user_type: "volunteer",
        speaks_arabic: values.speaks_arabic === "true",
        health_concerns: values.health_concerns,
      });

      toast.success(t("COMMON.TOAST.REGISTRATION_SUCCESSFUL"));
      resetForm();
      onClose?.();
      onShowEmailVerification?.(values.email, "register");
    } catch (error) {
      applyFormApiErrors(error, selectedLanguage, Object.keys(values), setFieldError, { username: "nickname" });
      reportRegistrationError(error);
    }
  };

  /* The GIS button's result: the profile decoded from the Google ID token,
     carrying the token as `social_token` (BE-160). The mandate step receives
     the same object, so its own `/social-auth/` call carries the token too. */
  const googleLogin = async (userData: SocialProfile) => {
    try {
      const checkUserResponse = await checkUserAsync({
        email: userData.email,
      });

      if (checkUserResponse?.data?.email?.is_new_user) {
        toast.info(t("COMMON.TOAST.WELCOME_NEW_USER"));
        onClose?.();
        onShowVolunteerMandateDetails?.(userData);
        return;
      }

      const response = await passSocialInfoMutation.mutateAsync({
        ...userData,
        user_type: userType,
        social_media_provider: "google",
      });
      setUser(response.data);
      toast.success(t("COMMON.TOAST.LOGIN_SUCCESSFUL"));
      onClose?.();
    } catch (error) {
      reportRegistrationError(error);
    }
  };

  const isBusy =
    registerMutation.isPending ||
    passSocialInfoMutation.isPending ||
    genderLoading ||
    relationshipLoading;

  return {
    selectedLanguage,
    setUser,
    isUnder18,
    setIsUnder18,
    nicknameAvailability,
    setNicknameAvailability,
    nicknameCheckTimeoutRef,
    registerMutation,
    checkUserMutation,
    passSocialInfoMutation,
    genderData,
    genderLoading,
    relationshipData,
    relationshipLoading,
    genderOptions,
    relationshipOptions,
    initialValues,
    requiredWhenUnder18,
    validationSchema,
    checkNicknameAvailability,
    reportRegistrationError,
    handleSubmit,
    googleLogin,
    isBusy,
  };
}
