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

import { useEffect, useState, useCallback, useMemo, useRef } from "react";
import { FormikHelpers, FormikProps } from "formik";
import { useRouter } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";
import { setNavState, NAV_STATE_KEYS } from "@/lib/navigationState";
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 {
  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, YupDigitsOnlyOptional, createPhoneNumberSchema } from "@/features/shared/schemas";
import {
  sortOrgTypeOptions,
  type OrgTypeOption,
} from "@/data/orgTypes";
import { toChoiceOptions } from "@/lib/choices";
import {
  EMPTY_NICKNAME_AVAILABILITY,
  type NicknameAvailability,
  USERNAME_PATTERN,
} from "@/features/shared/nicknameAvailability";
import { entitiesRegistrationInitialValues } from "./entitiesRegistrationValues";
import { logRequestError } from "@/lib/api/logError";
import {
  areDocumentsWithinSizeLimit,
  signupLicenseNumberRequired,
  signupLicenseUploadRequired,
  whenValue,
  type YupWhenValue,
} from "@/features/shared/formRules";

/**
 * Organisation sign-up: the form's values, the three dropdown lookups and the
 * register / Google / LinkedIn paths.
 */
export function useEntitiesRegistration(accountType: "team" | "organization" = "organization") {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const setUser = useAuthStore((s) => s.setUser);


  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 isVolunteerTeamJoin = accountType === "team";
  const volunteerTeamPrefilled = useRef(false);
  const formikRef = useRef<FormikProps<typeof initialValues> | null>(null);

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

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

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

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

  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 then sorted into the order the client asked for; the API
  // returns them in insertion order, which is not it.
  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]);

  useEffect(() => { setNavState(NAV_STATE_KEYS.joinAsVolunteerTeam, isVolunteerTeamJoin); }, [isVolunteerTeamJoin]);

  const initialValues = entitiesRegistrationInitialValues;

  const validationSchema = Yup.object({
    ...organizationSignupRules(),
    /* The organization / team name (sent as `company_name`): `max:255` in
       RegisterRequest and on the account edit form. 30 cut off most Arabic
       entity names. */
    first_name: YupStringMaxLength(255).concat(YupRequiredString),
    /* A team never picks a type: `/choices/org_type/` leaves «Volunteer Team»
       out and the form hides the field, so requiring it blocked every team
       sign-up on an error no one could see. A team 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();
      }
    ),
    nickname: YupStringMaxLength(30).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),
    email: YupEmail,
    documents: Yup.array().test("fileSizeAndRequired", t("COMMON.FILE_MAX_SIZE_MB", { size: 10 }), 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") || "Required field",
        });
      }
      return areDocumentsWithinSizeLimit(files, 10 * 1024 * 1024);
    }),
    password: YupStrongPassword,
    termsAccepted: Yup.boolean()
      .required(t("COMMON.REQUIRED.FIELD"))
      .oneOf([true], t("COMMON.TERMS_ACCEPTANCE_REQUIRED")),
  });

  /*
   * `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);
      }
    };
  }, []);

  const handleSubmit = async (
    values: typeof initialValues,
    { resetForm, setFieldError }: FormikHelpers<typeof initialValues>
  ) => {
    const formData = new FormData();
    appendOrganizationSignupExtras(formData, values);
    formData.append("company_name", values.first_name ?? "");
    appendSignupAccountType(formData, isVolunteerTeamJoin, values.organizer_type);
    formData.append("email", values.email ?? "");
    formData.append("password", values.password ?? "");
    formData.append("phone_number", values.phone_number ?? "");
    formData.append("country_code", values.country_code ?? "");
    formData.append("license_number", values.license_number ?? "");
    // «اسم المستخدم» — 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 ?? "");

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

    try {
      await registerMutation.mutateAsync(formData);
      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, { company_name: "first_name", 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"));
      }
    }
  };

  /**
   * What of this form can be carried into /complete-details so the organizer
   * does not answer the same questions twice. Uploaded documents are `File`
   * objects and cannot be serialized, so the certificate is asked for again.
   */
  const organizationPrefill = (values: typeof initialValues) => ({
    company_name: values.first_name,
    organizer_type: values.organizer_type,
    phone_number: values.phone_number,
    country_code: values.country_code,
    license_number: values.license_number,
    nickname: values.nickname,
    latitude: values.latitude,
    longitude: values.longitude,
  });

  // 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 organization that arrives without its company
   * details, so a new email is routed through /complete-details 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("organization", pendingPrefillRef.current);
        router.push(socialOnboardingRoute("organization"));
        return;
      }

      const response = await passSocialInfoMutation.mutateAsync({
        ...profile,
        user_type: signupUserType(isVolunteerTeamJoin),
      });
      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 googleLoginForOrganizer = (profile: SocialProfile) => continueSocialSignup(profile);

  /**
   * The social path hands the tab to Google and `orgTypeLoading`
   * blocks the form until its dropdown has options, so both keep the overlay.
   * Submitting the form reports itself inside the submit button.
   */
  const isBlockingLoading =
    // Deliberately not checkUserMutation: the nickname availability check
    // runs on every keystroke and reports itself inside the field.
    passSocialInfoMutation.isPending || orgTypeLoading;

  const isFormLoading = registerMutation.isPending || isBlockingLoading;

  return {
    router,
    selectedLanguage,
    setUser,
    nicknameAvailability,
    setNicknameAvailability,
    nicknameCheckTimeoutRef,
    isVolunteerTeamJoin,
    volunteerTeamPrefilled,
    formikRef,
    registerMutation,
    checkUserMutation,
    passSocialInfoMutation,
    orgTypeData,
    orgTypeLoading,
    orgTypeOptions,
    visibleOrgTypeOptions,
    initialValues,
    validationSchema,
    checkNicknameAvailability,
    handleSubmit,
    organizationPrefill,
    pendingPrefillRef,
    continueSocialSignup,
    googleLoginForOrganizer,
    isBlockingLoading,
    isFormLoading,
  };
}
