"use client";
import { applyFormApiErrors } from "@/features/shared/formApiErrors";
import { organizationSignupExtras, organizationSignupRules, appendOrganizationSignupExtras, appendSignupAccountType } from "./organizationSignupRules";

import {
  type CompleteDetailsValues,
  type SocialUserData,
} from "./completeDetailsTypes";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  useConsumedSocialPrefill,
  useStashedSocialProfile,
} from "./useStashedSocialProfile";
import { useRouter } from "next/navigation";
import { FormikHelpers, FormikProps } 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,
} from "@/features/auth/services/authApi";
import {
  getApiErrorMessage,
  getApiErrorMessages,
  getApiFieldErrors,
  isApiSuccess,
} from "@/lib/api/errors";
import { YupRequiredString, YupStringMaxLength, YupDigitsOnlyOptional, createPhoneNumberSchema } from "@/features/shared/schemas";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import {
  applyPrefill,
  clearSocialSignupState,
  isSocialCredentialRejected,
} from "@/lib/auth/socialSignup";
import {
  sortOrgTypeOptions,
  type OrgTypeOption,
} from "@/data/orgTypes";
import { NAV_STATE_KEYS } from "@/lib/navigationState";
import { useNavState } from "@/hooks/useNavState";
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 {
  areDocumentsWithinSizeLimit,
  signupLicenseNumberRequired,
  signupLicenseUploadRequired,
  whenValue,
  type YupWhenValue,
} from "@/features/shared/formRules";
import { DEFAULT_DIAL_CODE } from "@/data/defaultCountry";

/**
 * The social sign-up completion screen.
 *
 * The prefill comes from whichever provider sent the user here, stashed by the
 * login flow, which is why it is read on mount rather than passed in.
 */
export function useCompleteDetails() {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const setUser = useAuthStore((s) => s.setUser);

  // The OAuth payload arrived via `location.state` in the React app; the login
  // and sign-up screens now stash it in sessionStorage before navigating here.
  /* The provider profile stashed before the OAuth redirect, through the shared
     hook — see `useStashedSocialProfile` for why this is a mount effect and
     why its `setState` is accepted there once instead of here. */
  const userData = useStashedSocialProfile<SocialUserData>();

  // Answers already typed into the organizer sign-up form before the visitor
  // clicked Google / LinkedIn, so they are not asked for a second time. The
  // certificate is the exception — a File cannot survive sessionStorage.

  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);

  // Read once and consume: the JoinUs "Volunteer Team" shortcut sets this
  // right before pushing here. `useState`'s lazy initializer runs
  // synchronously during the first render, so the flag is settled before it's
  // needed below — no effect-timing race.
  const teamIntent = useNavState<boolean>(NAV_STATE_KEYS.joinAsVolunteerTeam);
  const isVolunteerTeamJoin = teamIntent === true;
  const volunteerTeamPrefilled = useRef(false);
  const formikRef = useRef<FormikProps<CompleteDetailsValues> | null>(null);

  /* Consumed through the shared hook — see `useConsumedSocialPrefill`, which
     holds the one accepted `setState`-in-an-effect for this read. */
  const prefill = useConsumedSocialPrefill("organization");

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

  const { data: orgTypeData, isLoading: orgTypeLoading } = useQuery({
    queryKey: ["org-type-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("org_type"),
    enabled: !!selectedLanguage,
  });

  // Transform API responses into options for SelectInput
  const orgTypeOptions: OrgTypeOption[] = useMemo(
    () =>
      toChoiceOptions(orgTypeData?.data, selectedLanguage, (item) =>
        String(item.id)
      ),
    [orgTypeData, selectedLanguage]
  );

  // The visible dropdown never offers "Volunteer Team" — that path only ever
  // reaches this form via the dedicated JoinUs shortcut, which skips the
  // field entirely and sets the value in the background instead. The rest are
  // sorted into the client's order, same as the entities form.
  const visibleOrgTypeOptions = useMemo(
    () =>
      sortOrgTypeOptions(
        orgTypeOptions.filter(
          (o: (typeof orgTypeOptions)[number]) => o.rawValue !== "Volunteer Team"
        )
      ),
    [orgTypeOptions]
  );

  // The "Volunteer Team" org_type choice is backend-driven and only known
  // once orgTypeOptions loads, so this can't be a Formik initialValue — it's
  // applied imperatively, once, as soon as the matching option arrives.
  useEffect(() => {
    if (!isVolunteerTeamJoin || volunteerTeamPrefilled.current) return;
    const volunteerTeam = orgTypeOptions.find(
      (o: (typeof orgTypeOptions)[number]) => o.rawValue === "Volunteer Team"
    );
    if (!volunteerTeam) return;
    volunteerTeamPrefilled.current = true;
    formikRef.current?.setFieldValue("organizer_type", volunteerTeam.value);
  }, [isVolunteerTeamJoin, orgTypeOptions]);

  const initialValues: CompleteDetailsValues = applyPrefill(
    {
      ...organizationSignupExtras,
      organizer_type: "", // Empty by default to enforce selection
      phone_number: "",
      /* Kuwait by default, declared here rather than seeded by
         `CountryCodeSelect` from a mount effect. See `DEFAULT_DIAL_CODE`. */
      country_code: DEFAULT_DIAL_CODE,
      documents: [],
      license_number: "",
      company_name: "",
      nickname: "",
      latitude: "",
      longitude: "",
      termsAccepted: false,
    },
    prefill
  );

  const validationSchema = Yup.object({
    ...organizationSignupRules(),
    /* A team never picks a type (the field is hidden and `/choices/org_type/`
       leaves «Volunteer Team» out); it always needs the licence. */
    organizer_type: isVolunteerTeamJoin ? Yup.string() : Yup.string().concat(YupRequiredString),
    license_number: YupDigitsOnlyOptional(100).when(
      "organizer_type",
      (organizer_type: YupWhenValue, schema: Yup.StringSchema) => {
        return signupLicenseNumberRequired(isVolunteerTeamJoin, orgTypeOptions, whenValue(organizer_type))
          ? schema.required(t("COMMON.REQUIRED.FIELD"))
          : schema.notRequired();
      }
    ),
    company_name: YupStringMaxLength(255).concat(YupRequiredString),
    nickname: YupStringMaxLength(50).concat(YupRequiredString)
      .matches(USERNAME_PATTERN, t("COMMON.USERNAME_FORMAT"))
      .test("nickname-availability", t("COMMON.USERNAME_TAKEN"), function () {
        if (!this.parent.nickname) return true;
        return nicknameAvailability.available !== false;
      }),
    phone_number: Yup.string().when(
      "country_code",
      (country_code: YupWhenValue) =>
        createPhoneNumberSchema(whenValue(country_code))
    ),
    country_code: Yup.string().concat(YupRequiredString),
    // The upload is optional for تعليمي / حكومي / مجتمع only; sizes are
    // validated whenever files are present, either way.
    documents: Yup.array().test(
      "fileSizeAndRequired",
      t("COMMON.FILE.TOO.LARGE"),
      function (files) {
        // Optional for تعليمي / حكومي / مجتمع; required for every other
        // type (`isLicenseUploadRequired`).
        const uploadRequired = signupLicenseUploadRequired(
          isVolunteerTeamJoin,
          orgTypeOptions,
          this.parent?.organizer_type
        );
        if (!files || files.length === 0) {
          if (!uploadRequired) return true;
          return this.createError({
            message: t("COMMON.REQUIRED.FIELD") || t("COMMON.FILE.TOO.LARGE"),
          });
        }
        return areDocumentsWithinSizeLimit(files);
      }
    ),
    termsAccepted: Yup.boolean()
      .required(t("COMMON.REQUIRED.FIELD"))
      .oneOf([true], t("COMMON.TERMS_ACCEPTANCE_REQUIRED")),
  });

  // 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: CompleteDetailsValues,
    { resetForm, setFieldError }: FormikHelpers<CompleteDetailsValues>
  ) => {
    /* BE-160 — `/social-auth/` takes identity only from `social_token`. A
       stash without one (lost, or written before it existed) cannot succeed,
       so restart the provider sign-in instead of posting a certain 422. */
    if (!userData?.social_token) {
      endSocialSignup(t("COMMON.TOAST.SOCIAL_SESSION_EXPIRED"));
      return;
    }

    const formData = new FormData();
    appendOrganizationSignupExtras(formData, values);

    formData.append("phone_number", values.phone_number ?? "");
    formData.append("country_code", values.country_code ?? "");
    appendSignupAccountType(formData, isVolunteerTeamJoin, values.organizer_type);
    formData.append("license_number", values.license_number ?? "");
    formData.append("company_name", values.company_name ?? "");
    // «اسم المستخدم» — required and fixed for an organization or team.
    formData.append("username", values.nickname.trim());
    formData.append("nickname", values.nickname.trim());
    formData.append("latitude", values.latitude ?? "");
    formData.append("longitude", values.longitude ?? "");

    // Append social media data from userData
    if (userData) {
      formData.append("social_token", userData.social_token);
      formData.append("email", userData.email ?? "");
      formData.append("first_name", userData.first_name ?? "");
      formData.append("last_name", userData.last_name ?? "");
      formData.append(
        "social_media_provider",
        userData.social_media_provider ?? ""
      );
      formData.append("social_media_id", userData.social_media_id ?? "");
      formData.append(
        "social_profile_pic_url",
        userData.social_profile_pic_url ?? ""
      );
    }

    // Append multiple documents
    if (values.documents) {
      for (let i = 0; i < values.documents.length; i++) {
        formData.append("documents[]", values.documents[i]);
      }
    }

    try {
      const response = await passSocialInfoMutation.mutateAsync(formData);
      if (!isApiSuccess(response)) {
        toast.error(
          response?.msg || t("COMMON.TOAST.PROFILE_COMPLETION_FAILED")
        );
        return;
      }
      const signedIn = userFromAuthResponse(response);
      if (!signedIn) {
        toast.error(t("COMMON.TOAST.PROFILE_COMPLETION_FAILED"));
        return;
      }
      setUser(signedIn);
      clearSocialSignupState();
      toast.success(t("COMMON.TOAST.PROFILE_COMPLETION"));
      resetForm();
      router.push("/");
    } catch (err) {
      /* BE-164 — the account was created, but a new organization or team
         gets no session until an admin approves it (PDF p.7: approval is
         independent of sign-up). The reason arrives under
         `organization_status`; it is the success path, not a failure to
         retry — resubmitting would only hit the same answer. */
      const approval = getApiFieldErrors(err, selectedLanguage).organization_status;
      if (approval) {
        clearSocialSignupState();
        toast.success(t("COMMON.TOAST.PROFILE_COMPLETION"));
        toast.info(approval);
        resetForm();
        router.push("/");
        return;
      }
      applyFormApiErrors(err, selectedLanguage, Object.keys(values), setFieldError, { username: "nickname" });
      /* 401 — the provider credential expired while the form was filled in
         (a LinkedIn ticket lives ~600 s). Only a fresh sign-in mints another.
         503 falls through: its `msg` asks for a retry and the form keeps the
         answers. */
      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.PROFILE_COMPLETION_FAILED"));
      }
    }
  };

  /** The social credential is gone: drop the stash and restart the sign-in. */
  function endSocialSignup(message: string) {
    toast.error(message);
    clearSocialSignupState();
    router.replace("/login?user_type=organization");
  }

  return {
    router,
    selectedLanguage,
    setUser,
    userData,
    prefill,
    passSocialInfoMutation,
    checkUserMutation,
    nicknameAvailability,
    setNicknameAvailability,
    nicknameCheckTimeoutRef,
    isVolunteerTeamJoin,
    volunteerTeamPrefilled,
    formikRef,
    orgTypeData,
    orgTypeLoading,
    orgTypeOptions,
    visibleOrgTypeOptions,
    initialValues,
    validationSchema,
    checkNicknameAvailability,
    handleSubmit,
  };
}
