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

import { useEffect, useMemo, useState, useCallback, useRef } from "react";
import { FormikHelpers } from "formik";
import { useRouter } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as Yup from "yup";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import {
  appendRegisterPayload,
  registerRequest,
  checkUserRequest,
  readUsernameAvailability,
  usernameAvailabilityQuery,
  passSocialInfoRequest,
  getDropdownChoicesRequest,
} from "@/features/auth/services/authApi";
import { getApiErrorMessage, getApiErrorMessages, isApiSuccess } from "@/lib/api/errors";
import {
  SocialProfile,
  setSocialPrefill,
  socialOnboardingRoute,
  stashSocialProfile,
} from "@/lib/auth/socialSignup";
import { YupEmail, YupRequiredString, YupStringMaxLength, YupStrongPassword, YupCivilId, MIN_SIGNUP_AGE, createPhoneNumberSchema, calculateAgeFromDob } from "@/features/shared/schemas";
import { YupDateOfBirth, maxDateOfBirthFor } from "@/features/shared/schemas";
import {
  individualInitialValues,
  } from "./individualRegistrationValues";
import { getTrainerRequestSettings } from "@/features/trainer/services/trainerApi";
import {
  DEFAULT_TRAINER_SETTINGS,
  MIN_TRAINER_AGE,
  TRAINER_REQUEST_LIVE,
  appendTrainerRequest,
  isOldEnoughForTrainer,
  trainerRequestSchema,
} from "@/features/trainer/trainerRequest";
import {
  findNationalityResidency,
  nationalityNeedsPassport,
  speaksArabicToPayload,
} from "@/data/Constants";
import { toChoiceOptions } from "@/lib/choices";
import {
  EMPTY_NICKNAME_AVAILABILITY,
  type NicknameAvailability,
  USERNAME_PATTERN,
} from "@/features/shared/nicknameAvailability";
import { logRequestError } from "@/lib/api/logError";
import type { RegisterPayload } from "@/features/auth/services/authApi";
import {
  whenValue,
  type YupWhenValue,
} from "@/features/shared/formRules";
import { emergencyContactPayload } from "@/features/auth/emergencyContact";
import { isUnderageToday } from "@/lib/age";

/** Extracted from the component of the same name. */
export function useIndividualRegistration() {
  const { t } = useTranslation();
  const router = useRouter();
  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<NodeJS.Timeout | null>(null);

  // TanStack Query mutations
  const registerMutation = useMutation({
    mutationFn: registerRequest,
  });

  const checkUserMutation = useMutation({
    mutationFn: checkUserRequest,
  });

  const passSocialInfoMutation = useMutation({
    mutationFn: passSocialInfoRequest,
  });

  // Fetch choices
  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,
  });

  // BE-95 — the dashboard's two switches decide what the trainer block requires.
  const { data: trainerSettingsData } = useQuery({
    queryKey: ["trainer-request-settings"],
    queryFn: getTrainerRequestSettings,
    enabled: TRAINER_REQUEST_LIVE,
    staleTime: 5 * 60 * 1000,
  });
  const trainerSettings = trainerSettingsData?.data ?? DEFAULT_TRAINER_SETTINGS;

  const genderOptions =
    toChoiceOptions(genderData?.data, selectedLanguage, (item) => item.id);

  const relationshipOptions =
    toChoiceOptions(relationshipData?.data, selectedLanguage, (item) => item.id);

  const initialValues = individualInitialValues;

  const calculateAge = calculateAgeFromDob;

  // Recomputed only on mount: a new Date object every render would make the
  // picker think its bounds changed.
  const maxBirthDate = useMemo(() => maxDateOfBirthFor(MIN_SIGNUP_AGE), []);

  const validationSchema = Yup.object({
    ...individualSignupExtrasRules(),
    first_name: YupStringMaxLength(30)
      .concat(YupRequiredString),
    last_name: YupStringMaxLength(30)
      .concat(YupRequiredString),
    nickname: YupStringMaxLength(30)
      .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),
    email: YupEmail,
    password: YupStrongPassword,
    /*
     * Which identifier is mandatory follows the nationality choice, the same
     * way `RegisterRequest::validateIdentityDocument()` decides it server-side:
     * a Kuwaiti or a non-Kuwaiti resident gives a civil ID, a non-Kuwaiti
     * non-resident gives a passport number instead.
     */
    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"]).concat(YupRequiredString),
    health_concerns: Yup.string().oneOf(["yes", "no"]).concat(YupRequiredString),
    profile_pic: Yup.array().max(1).of(Yup.mixed<File>().test("profile-image", () => t("COMMON.REVIEW_IMAGE_LIMIT"), file => !file || (["image/jpeg", "image/png", "image/webp"].includes(file.type) && file.size <= 10 * 1024 * 1024))),
    receive_reminder_emails: Yup.boolean(),
    termsAccepted: Yup.boolean()
      .required(t("COMMON.REQUIRED.FIELD"))
      .oneOf([true], t("COMMON.TERMS_ACCEPTANCE_REQUIRED")),
    emergency_contact_name: Yup.string().when("dob", {
      is: (dob: string) => {
        const age = calculateAge(dob);
        return age !== null && age < 18;
      },
      then: () => YupStringMaxLength(100).concat(YupRequiredString),
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_country_code: Yup.string().when("dob", {
      is: (dob: string) => {
        const age = calculateAge(dob);
        return age !== null && age < 18;
      },
      then: () => YupRequiredString,
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_phone: Yup.string().when("dob", {
      is: (dob: string) => {
        const age = calculateAge(dob);
        return age !== null && age < 18;
      },
      then: () => 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);
        }
      ),
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_civil_id: Yup.string().when("dob", {
      is: (dob: string) => {
        const age = calculateAge(dob);
        return age !== null && age < 18;
      },
      then: () => YupCivilId,
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_relationship: Yup.string().when("dob", {
      is: (dob: string) => {
        const age = calculateAge(dob);
        return age !== null && age < 18;
      },
      then: () => YupRequiredString,
      otherwise: () => Yup.string().notRequired(),
    }),
    // Reported on the toggle itself, where the choice was made.
    wants_trainer: Yup.boolean().test(
      "trainer-age",
      () => t("COMMON.TRAINER_AGE_REQUIRED", { age: MIN_TRAINER_AGE }),
      function (value) {
        return !value || isOldEnoughForTrainer(this.parent.dob);
      }
    ),
    ...trainerRequestSchema(
      trainerSettings,
      (parent) => TRAINER_REQUEST_LIVE && parent.wants_trainer === true
    ),
  });

  const handleSubmit = async (
    values: typeof initialValues,
    { resetForm, setFieldError }: FormikHelpers<typeof initialValues>
  ) => {
    try {
      // One dropdown on screen, two fields on the wire. The identifier that
      // does not apply is sent empty rather than left out, so switching the
      // choice after typing cannot carry a stale civil ID or passport through.
      const residency = findNationalityResidency(values.nationality);
      const usesPassport = residency?.identifier === "passport_number";

      // The trainer block and the UI-only toggles are not sent as-is: an API
      // without BE-95 rejects any key it does not know.
      const {
        profile_pic,
        show_real_name,
        wants_trainer,
        trainer_types,
        trainer_certificate,
        bank_account_holder_name,
        bank_id,
        bank_name,
        iban,
        iban_confirmation,
        bank_account_ownership,
        ...accountValues
      } = values;
      const trainerValues = {
        trainer_types,
        trainer_certificate,
        bank_account_holder_name,
        bank_id,
        bank_name,
        iban,
        iban_confirmation,
        bank_account_ownership,
      };
      const requestsTrainer = TRAINER_REQUEST_LIVE && wants_trainer;

      /* `RegisterPayload`, not `Record<string, unknown>`: this is the body
         `POST /register/` validates, and naming it means a key the endpoint
         does not accept is an error here rather than a field Laravel drops
         without comment. */
      const payload: RegisterPayload = {
        ...accountValues,
        ...individualSignupExtrasPayload(values),
        ...(profile_pic[0] ? { profile_pic: profile_pic[0] } : {}),
        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 ?? "",

        speaks_arabic: speaksArabicToPayload(values.speaks_arabic),
        civil_id: usesPassport ? "" : values.civil_id,
        passport_number: usesPassport ? values.passport_number : "",
        user_type: "volunteer",

        ...(TRAINER_REQUEST_LIVE
          ? { show_real_name: requestsTrainer ? true : show_real_name }
          : {}),
      };

      if (requestsTrainer || profile_pic.length > 0) {
        // Multipart only when a file can ride along; JSON otherwise, as before.
        const formData = new FormData();
        appendRegisterPayload(formData, payload);
        if (requestsTrainer) {
          formData.append("wants_trainer", "1");
          appendTrainerRequest(formData, trainerValues);
        }
        await registerMutation.mutateAsync(formData);
      } else {
        await registerMutation.mutateAsync(payload);
      }

      toast.success(t("COMMON.TOAST.REGISTRATION_SUCCESSFUL"));
      resetForm();
      router.push(`/email-verification?email=${encodeURIComponent(values.email)}&otp_type=register`);
    } catch (err) {
      applyFormApiErrors(err, selectedLanguage, Object.keys(values), setFieldError, { username: "nickname" });
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
      }
    }
  };

  /** Answers carried into /volunteer-mandate-details for social signup. */
  const volunteerPrefill = (values: typeof initialValues) => ({
    ...individualSignupExtrasPayload(values),
    receive_reminder_emails: values.receive_reminder_emails,
    show_real_name: values.show_real_name,
    health_concerns: values.health_concerns,
    speaks_arabic: values.speaks_arabic,
    interest_ids: values.interest_ids,
    first_name: values.first_name,
    last_name: values.last_name,
    phone_number: values.phone_number,
    country_code: values.country_code,
    nickname: values.nickname,
    dob: values.dob,
    gender: values.gender,
    civil_id: values.civil_id,
    passport_number: values.passport_number,
    // The mandate screen uses the same combined dropdown value and performs
    // the API split itself when it submits.
    nationality: values.nationality,
    emergency_contact_name: values.emergency_contact_name,
    emergency_contact_phone: values.emergency_contact_phone,
    emergency_contact_country_code: values.emergency_contact_country_code,
    emergency_contact_civil_id: values.emergency_contact_civil_id,
    emergency_contact_relationship: values.emergency_contact_relationship,
  });

  // Set at click time, because the Google popup resolves long after the click
  // and the callback has no access to the Formik render scope.
  const pendingPrefillRef = useRef<Record<string, unknown>>({});

  /**
   * Both providers converge here. `/social-auth/` registers as well as logs in,
   * but it rejects a brand-new volunteer that arrives without `civil_id`, so a
   * new email is routed through the mandate screen first.
   */
  const continueSocialSignup = async (profile: SocialProfile) => {
    try {
      const checkUserResponse = await checkUserMutation.mutateAsync({
        email: profile.email,
      });

      if (checkUserResponse?.data?.email?.is_new_user) {
        toast.info(t("COMMON.TOAST.WELCOME_NEW_USER"));
        stashSocialProfile(profile);
        setSocialPrefill("volunteer", pendingPrefillRef.current);
        router.push(socialOnboardingRoute("volunteer"));
        return;
      }

      const response = await passSocialInfoMutation.mutateAsync({
        ...profile,
        user_type: "volunteer",
      });
      if (!isApiSuccess(response)) {
        toast.error(getApiErrorMessage(response, selectedLanguage, t("COMMON.TOAST.REGISTRATION_FAILED")));
        return;
      }

      setUser(response.data);
      toast.success(t("COMMON.TOAST.LOGIN_SUCCESSFUL"));
      router.push("/");
    } catch (err) {
      // The documented 400 here is "this email signs in with a password" —
      // worth showing verbatim rather than behind a generic failure toast.
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
      }
    }
  };

  /* The GIS button hands over the profile decoded from the Google ID token,
     with the token as `social_token` (BE-160) — see `SocialAuthButtons`. */
  const googleLoginForIndividual = (profile: SocialProfile) => continueSocialSignup(profile);

  /*
   * `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 500 ms wait; depending on the hoisted function is both stable and
   * complete, so the dependency list is honest rather than trimmed.
   */
  const checkUserAsync = checkUserMutation.mutateAsync;

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

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

      const nicknameRegex = USERNAME_PATTERN;
      if (!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);
      }
    };
  }, []);

  /**
   * The social paths hand the tab to Google or LinkedIn, so they keep the
   * overlay. Submitting the form reports itself inside the submit button.
   */
  const isSocialLoading =
    // Deliberately not checkUserMutation: the nickname availability check
    // runs on every keystroke and reports itself inside the field.
    passSocialInfoMutation.isPending;

  const isFormLoading = registerMutation.isPending || isSocialLoading;

  return {
    router,
    selectedLanguage,
    setUser,
    isUnder18,
    setIsUnder18,
    nicknameAvailability,
    setNicknameAvailability,
    nicknameCheckTimeoutRef,
    registerMutation,
    checkUserMutation,
    passSocialInfoMutation,
    genderData,
    genderLoading,
    relationshipData,
    relationshipLoading,
    trainerSettingsData,
    trainerSettings,
    genderOptions,
    relationshipOptions,
    initialValues,
    calculateAge,
    maxBirthDate,
    validationSchema,
    handleSubmit,
    volunteerPrefill,
    pendingPrefillRef,
    continueSocialSignup,
    googleLoginForIndividual,
    checkNicknameAvailability,
    isSocialLoading,
    isFormLoading,
  };
}
