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

import { useCallback, useEffect, useRef, useState } from "react";
import {
  useConsumedSocialPrefill,
  useStashedSocialProfile,
} from "./useStashedSocialProfile";
import { useRouter } from "next/navigation";
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,
  type SocialAuthPayload,
} from "@/features/auth/services/authApi";
import {
  getApiErrorMessage,
  getApiErrorMessages,
  isApiSuccess,
} from "@/lib/api/errors";
import {
  findNationalityResidency,
  nationalityNeedsPassport,
  speaksArabicToPayload,
} from "@/data/Constants";
import { YupCivilId, YupRequiredString, YupStringMaxLength, 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 {
  applyPrefill,
  clearSocialSignupState,
  isSocialCredentialRejected,
  type SocialProfile,
} from "@/lib/auth/socialSignup";

import { type MandateFormValues } from "./volunteerMandateParts";
import { type VolunteerMandateDetailsProps } from "./VolunteerMandateDetails";
import { toChoiceOptions } from "@/lib/choices";
import {
  EMPTY_NICKNAME_AVAILABILITY,
  type NicknameAvailability,
  USERNAME_PATTERN,
} from "@/features/shared/nicknameAvailability";
import { logRequestError } from "@/lib/api/logError";
import { userFromAuthResponse } from "@/features/auth/authSession";
import {
  whenValue,
  type YupWhenValue,
} from "@/features/shared/formRules";
import { DEFAULT_DIAL_CODE } from "@/data/defaultCountry";
import { emergencyContactPayload } from "@/features/auth/emergencyContact";

/**
 * The volunteer-team mandate form: its values, the under-18 branch that makes
 * the guardian fields required, and the submit.
 */
export function useVolunteerMandate({
  userData: propUserData,
  onClose,
}: VolunteerMandateDetailsProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const setUser = useAuthStore((s) => s.setUser);

  // Rendered as a page the OAuth payload comes from sessionStorage (the login /
  // sign-up screens stash it there); rendered as a modal it arrives as a prop.
  /*
   * The OAuth payload stashed under `OAUTH_USER_KEY` before the redirect —
   * `SocialProfile`, the same shape `stashSocialProfile()` writes. Only the
   * name and email are read out of it, both optional on that type.
   *
   * Read through the shared `useStashedSocialProfile`, which is where the
   * `sessionStorage` read and its one accepted `setState`-in-an-effect live.
   * It runs even when `propUserData` is supplied — the modal case — which the
   * old effect skipped; harmless, because `propUserData` wins below.
   */
  const storedUserData = useStashedSocialProfile<SocialProfile>();
  const userData = propUserData || storedUserData;

  // Answers already typed into the individual sign-up form before the visitor
  // clicked Google / LinkedIn, so they are not asked for a second time.

  const passSocialInfoMutation = useMutation({
    mutationFn: passSocialInfoRequest,
  });
  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;

  // Username availability check states
  const [nicknameAvailability, setNicknameAvailability] = useState<NicknameAvailability>(
    EMPTY_NICKNAME_AVAILABILITY
  );
  const nicknameCheckTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Fetch gender options from API
  const {
    data: genderData,
    isLoading: genderLoading,
    error: genderError,
  } = useQuery({
    queryKey: ["gender-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("gender"),
    enabled: !!selectedLanguage,
  });

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

  // Transform API response into options for SelectInput
  const genderOptions =
    // The id is what the backend expects as the submitted value.
    toChoiceOptions(genderData?.data, selectedLanguage, (item) => item.id);

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

  /* Consumed through the shared hook, skipped in the modal case exactly as the
     effect's `if (propUserData) return;` did — see
     `useConsumedSocialPrefill`. */
  const prefill = useConsumedSocialPrefill("volunteer", Boolean(propUserData));

  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  const initialValues: MandateFormValues = applyPrefill(
    {
      ...individualSignupExtras,
      receive_reminder_emails: true,
      first_name: userData?.first_name || "",
      last_name: userData?.last_name || "",
      phone_number: "",
      nickname: "",
      dob: "",
      gender: "",
      /* Kuwait by default, declared here rather than seeded by
         `CountryCodeSelect` from a mount effect. See `DEFAULT_DIAL_CODE`. */
      country_code: DEFAULT_DIAL_CODE,
      civil_id: "",
      passport_number: "",
      nationality: "",
      /** BE-77 — optional; only asked of non-Kuwaitis. */
      speaks_arabic: "",
      health_concerns: "",
      interest_ids: [] as string[],
      termsAccepted: false,
      emergency_contact_name: "",
      emergency_contact_phone: "",
      emergency_contact_country_code: DEFAULT_DIAL_CODE,
      emergency_contact_civil_id: "",
      emergency_contact_relationship: "",
    },
    prefill
  );

  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))
    ),
    dob: YupDateOfBirth(MIN_SIGNUP_AGE),
    country_code: Yup.string().concat(YupRequiredString),
    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),
    termsAccepted: Yup.boolean()
      .required(t("COMMON.REQUIRED.FIELD"))
      .oneOf([true], t("COMMON.TERMS_ACCEPTANCE_REQUIRED")),
    // Conditional validation for emergency contacts (required if under 18)
    emergency_contact_name: Yup.string().when("dob", {
      is: isUnderageToday,
      then: () => YupStringMaxLength(100).concat(YupRequiredString),
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_country_code: Yup.string().when("dob", {
      is: isUnderageToday,
      then: () => YupRequiredString,
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_phone: Yup.string().when("dob", {
      is: isUnderageToday,
      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: isUnderageToday,
      then: () => YupCivilId,
      otherwise: () => Yup.string().notRequired(),
    }),
    emergency_contact_relationship: Yup.string().when("dob", {
      is: isUnderageToday,
      then: () => YupRequiredString,
      otherwise: () => Yup.string().notRequired(),
    }),
  });

  // Debounced nickname availability check
  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);
      }
    };
  }, []);

  const handleSubmit = async (
    values: MandateFormValues,
    { resetForm, setFieldError }: FormikHelpers<MandateFormValues>
  ) => {
    try {
      /*
       * Without the provider profile there is no `email`, and
       * `/social-auth/` requires one — the request would 422 with a field
       * error the reader cannot act on. This screen is only reachable through
       * a social sign-in, so the guard should never fire; it is here because
       * `userData` is genuinely nullable (`propUserData || storedUserData`,
       * both of which can be null) and silently posting a payload with no
       * email is the worse failure.
       */
      if (
        !userData?.email ||
        !userData.social_media_provider ||
        !userData.social_token
      ) {
        /* No `social_token` (BE-160): a stash written by a build from before
           it existed, or a lost one. Nothing here can mint another — the
           provider sign-in has to be repeated. */
        if (userData?.email && !userData.social_token) {
          endSocialSignup(t("COMMON.TOAST.SOCIAL_SESSION_EXPIRED"));
          return;
        }
        toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
        return;
      }

      // `termsAccepted` is a consent checkbox this screen owns; `/social-auth/`
      // has no such field and should not be handed one. Everything else — the
      // provider profile plus civil_id / nickname / the volunteer details — is
      // what the endpoint documents.
      const residency = findNationalityResidency(values.nationality);
      const usesPassport = residency?.identifier === "passport_number";
      const profile: Record<string, unknown> = {
        ...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)),
        nationality: residency?.nationality ?? "",
        residency_status: residency?.residency_status ?? "",
        civil_id: usesPassport ? "" : values.civil_id,
        passport_number: usesPassport ? values.passport_number : "",
      };

      // BE-77 — same rule as the email signup form: the key is present only
      // when there is a real answer, because null means "passes every
      // audience" and `false` does not.
      const speaksArabic = speaksArabicToPayload(values.speaks_arabic);
      if (speaksArabic === undefined) {
        delete profile.speaks_arabic;
      } else {
        profile.speaks_arabic = speaksArabic;
      }
      delete profile.termsAccepted;
      /*
       * Annotated rather than inferred. `profile` is a
       * `Record<string, unknown>` the form mutates key by key, so spreading it
       * widens everything it touches — including `email`, which the endpoint
       * requires. Declaring the target type is what keeps the request checked
       * against the contract.
       *
       * `email` and `social_media_provider` are re-stated from the guarded
       * `userData` because both are **required** by `/social-auth/`
       * (`social_media_provider` is `Rule::in(['google', 'linkedin'])`) and
       * both are optional on the prop path — `MandatePrefillUser` is
       * `Partial<SocialAuthPayload>`. The guard above is what makes them
       * present; without it the request would 422 on a field the reader
       * cannot see or fix.
       */
      const finalUserData: SocialAuthPayload = {
        ...userData,
        ...profile,
        email: userData.email,
        social_media_provider: userData.social_media_provider,
        /* BE-160 — the provider credential from the first step, re-sent: this
           second `/social-auth/` call is verified exactly like the first. */
        social_token: userData.social_token,
        user_type: "volunteer",

      };

      const response = await passSocialInfoMutation.mutateAsync(finalUserData);
      if (!isApiSuccess(response)) {
        toast.error(getApiErrorMessage(response, selectedLanguage, t("COMMON.TOAST.REGISTRATION_FAILED")));
        return;
      }
      const signedIn = userFromAuthResponse(response);
      if (!signedIn) {
        toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
        return;
      }
      setUser(signedIn);
      clearSocialSignupState();
      toast.success(t("COMMON.TOAST.PROFILE_COMPLETION"));
      resetForm();
      if (onClose) {
        onClose();
      } else {
        router.push("/");
      }
    } catch (err) {
      applyFormApiErrors(err, selectedLanguage, Object.keys(values), setFieldError, { username: "nickname" });
      /* 401 — the Google ID token / LinkedIn ticket expired while the form was
         being filled in (the ticket lives ~600 s). Retrying cannot help, so
         say so and send them back to sign in. 503 falls through: its `msg`
         asks for a retry, and the form keeps the answers for it. */
      if (isSocialCredentialRejected(err)) {
        endSocialSignup(
          getApiErrorMessage(
            err,
            selectedLanguage,
            t("COMMON.TOAST.SOCIAL_SESSION_EXPIRED")
          )
        );
        return;
      }
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
      }
    }
  };

  /** The social credential is gone: drop the stash and restart the sign-in —
      in a modal by closing it (its host offers the sign-in again), as a page
      by going to /login. */
  function endSocialSignup(message: string) {
    toast.error(message);
    clearSocialSignupState();
    if (onClose) {
      onClose();
    } else {
      router.replace("/login?user_type=volunteer");
    }
  }

  return {
    genderError,
    genderLoading,
    router,
    selectedLanguage,
    setUser,
    storedUserData,
    userData,
    prefill,
    passSocialInfoMutation,
    checkUserMutation,
    nicknameAvailability,
    setNicknameAvailability,
    nicknameCheckTimeoutRef,
    relationshipData,
    relationshipLoading,
    genderOptions,
    relationshipOptions,
    initialValues,
    validationSchema,
    checkNicknameAvailability,
    handleSubmit,
  };
}
