"use client";

import { useEffect, useMemo, useSyncExternalStore } from "react";
import {
  forgetEmail,
  getRememberedEmail,
  getServerRememberedEmail,
  migrateLegacyCredentials,
  rememberEmail,
  subscribeRememberedEmail,
} from "@/features/auth/rememberedEmail";
import { FormikHelpers } from "formik";
import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { loginRequest, checkUserRequest, passSocialInfoRequest } from "@/features/auth/services/authApi";
import { getApiErrorMessage, getApiErrorMessages, getApiFieldErrors } from "@/lib/api/errors";
import { YupEmail, YupRequiredString } from "@/features/shared/schemas";
import * as Yup from "yup";

import { type LoginFormProps } from "./LoginForm";
import { logRequestError } from "@/lib/api/logError";
import { getApiErrorBody } from "@/lib/api/errors";
import { asOtpType } from "@/features/auth/services/authApi";
import {
  asSelfRegisterableUserType,
  type SocialAuthPayload,
} from "@/features/auth/services/authApi";
import type { SocialProfile } from "@/lib/auth/socialSignup";
import { userFromAuthResponse } from "@/features/auth/authSession";


/**
 * Sign-in behaviour: the remembered email, the password login, and the Google
 * and LinkedIn flows.
 *
 * All three social paths end in the same place — either a signed-in user or a
 * hand-off to registration for someone the backend has not seen before.
 */
/**
 * The login form's three fields.
 *
 * `rememberMe` does **two** things, and the second is the one that matters.
 *
 *  1. Client side, it decides whether the email is stashed for next time —
 *     the email only, never the password.
 *  2. Server side, it sets how long the session lasts.
 *     `AuthService::login()` reads it and issues a token for
 *     `config('fursa.token_expiry_days.remember')` = **30 days** instead of
 *     `…default` = **1 day**, and `AuthServiceProvider` rejects the token once
 *     `expires_at` passes. Unticked, the reader is signed out again tomorrow.
 *
 * This comment used to call it "a client-only convenience", which was wrong:
 * it is part of the submitted body because the API acts on it, not merely
 * because the field is `nullable` there.
 */
export interface LoginFormValues {
  email: string;
  password: string;
  rememberMe: boolean;
}

export function useLoginForm({
  userType = null,
  returnTo = "/",
  isModal = false,
  onClose,
  onShowEmailVerification,
  onShowVolunteerMandateDetails,
}: LoginFormProps) {
  const router = useRouter();
  const { t } = useTranslation();
  const setUser = useAuthStore((s) => s.setUser);
  const selectedLanguage = useLanguageStore((s) => s.language);

  /*
   * The remembered email, subscribed to rather than copied.
   *
   * `localStorage` owns it; this form held a `useState` seeded empty and
   * overwritten by a mount effect, which both tripped
   * `react-hooks/set-state-in-effect` and painted one frame with the field
   * blank before filling it in. `features/auth/rememberedEmail` exposes it as
   * an external store with its own server snapshot, so the value is correct in
   * the render that produces it — and a sign-out in another tab now clears the
   * prefill here too.
   */
  const rememberedEmail = useSyncExternalStore(
    subscribeRememberedEmail,
    getRememberedEmail,
    getServerRememberedEmail
  );

  const initialFormValues: LoginFormValues = useMemo(
    () => ({
      email: rememberedEmail ?? "",
      password: "",
      /* Checked iff an email is remembered — the same thing the two
         `setInitialFormValues` calls encoded. */
      rememberMe: rememberedEmail !== null,
    }),
    [rememberedEmail]
  );

  const validationSchema = Yup.object({
    email: YupEmail,
    password: YupRequiredString,
  });

  /* Drop any clear-text `{ email, password }` an older build left behind,
     keeping the email. A genuine effect — it writes to an external system and
     sets no state; the store notifies its own subscribers. */
  useEffect(() => {
    migrateLegacyCredentials();
  }, []);

  const loginMutation = useMutation({
    mutationFn: loginRequest,
  });

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

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

  const handleSubmit = async (
    values: LoginFormValues,
    { resetForm }: FormikHelpers<LoginFormValues>
  ) => {
    try {
      const response = await loginMutation.mutateAsync(values);
      /*
       * Through `userFromAuthResponse`, never by reaching into the envelope
       * here — because the two sign-in endpoints nest differently and this
       * file got it wrong in both directions already.
       *
       * `POST /login/` answers `data: { data: { …user, auth_token } }` while
       * `POST /social-auth/` answers `data: { …user, auth_token }`. Reading
       * `response.data` for both looked like the fix and left the password
       * path handing `setUser` a record with no token: the «Login failed»
       * toast on correct credentials, with a 200 and a valid token in the
       * reply. The reader now accepts either, and
       * `tests/authSession.test.ts` holds both shapes.
       */
      const userData = userFromAuthResponse(response);
      if (!userData) {
        /* No token in the envelope is a failed sign-in however the status
           line reads; reporting success here is what hid the original bug. */
        toast.error(t("COMMON.TOAST.LOGIN_FAILED"));
        return;
      }

      /* Remember the email only — never the password; see
         `features/auth/rememberedEmail`. Through the store's writers, so the
         subscribed prefill updates with it. */
      if (values.rememberMe) {
        rememberEmail(values.email);
      } else {
        forgetEmail();
      }

      /*
       * BE-129 — was this a *second* account being added?
       *
       * Read before `setUser`, which clears the intent as part of signing in.
       * It decides how we leave: a router push keeps the React Query cache,
       * and every entry in it was answered for the account that was active a
       * moment ago — `is_registered`, `relationship_tags`, the notification
       * count. Switching reloads for exactly this reason, and arriving by
       * adding an account is the same arrival.
       */
      const wasAddingAccount = useAuthStore.getState().addingAccount;

      setUser(userData);
      toast.success(t("COMMON.TOAST.LOGIN_SUCCESSFUL"));

      resetForm({
        values: {
          email: values.rememberMe ? values.email : "",
          password: "",
          rememberMe: values.rememberMe,
        },
      });

      if (isModal) {
        onClose?.();
        if (wasAddingAccount) window.location.reload();
      } else if (wasAddingAccount) {
        window.location.assign(returnTo);
      } else {
        router.push(returnTo);
      }
    } catch (err) {
      const fieldErrors = getApiFieldErrors(err, selectedLanguage);
      const messages = Object.values(fieldErrors);
      // An unverified account is rejected at login (403, `data.action ===
      // "verify_otp"`) — send it to the OTP step instead of a dead-end toast.
      // That structured field is the authoritative signal; the message-text
      // regex is kept only as a fallback for a response shape that omits it.
      // It's already stale once — the API's wording is "is not activated",
      // which this pattern doesn't match ("active" != "activat[ed]") — so
      // don't let it become the only path again.
      const errorData = getApiErrorBody(err)?.data;
      const isInactive =
        errorData?.action === "verify_otp" ||
        messages.some((message) => /is not activ|غير مفع|غير نشط/i.test(message));

      if (errorData?.error_code === "user_banned") {
        // The ban popup (`BanNoticeModal`, opened by the API client) already
        // says it — a toast would repeat the same sentence.
      } else if (isInactive) {
        const email = errorData?.email || values.email || "";
        const otpType = asOtpType(errorData?.otp_type);
        toast.error(t("COMMON.TOAST.USER_NOT_ACTIVE"));
        if (isModal && onShowEmailVerification) {
          onClose?.();
          onShowEmailVerification(email, otpType);
        } else {
          router.push(
            `/email-verification?email=${encodeURIComponent(email)}&otp_type=${encodeURIComponent(otpType)}`
          );
        }
      } else if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        // `msg` carries refusals with no field, e.g. `account_deactivated`
        // (403), whose text names the administration's contact address.
        toast.error(getApiErrorMessage(err, selectedLanguage, t("COMMON.TOAST.LOGIN_FAILED")));
      }
      logRequestError("Login failed:", err);
    }
  };

  /**
   * A social login for an unknown email needs the mandate/details step. On the
   * standalone page that is a route; in a modal the host swaps the body.
   */
  const routeNewSocialUser = (userData: SocialProfile) => {
    if (isModal && onShowVolunteerMandateDetails) {
      onClose?.();
      onShowVolunteerMandateDetails(userData);
      return;
    }
    sessionStorage.setItem("oauth_user", JSON.stringify(userData));
    if (userType === "volunteer") {
      router.push("/volunteer-mandate-details");
    } else if (userType === "organization") {
      router.push("/complete-details");
    } else {
      router.push("/joinus");
    }
  };

  /**
   * The GIS button's result (`SocialAuthButtons`): the profile decoded from
   * the Google ID token, carrying the token itself as `social_token` — which
   * `/social-auth/` verifies (BE-160) and `routeNewSocialUser` stashes for the
   * onboarding screen's call.
   */
  const googleLogin = async (userData: SocialProfile) => {
    try {
      const checkUserResponse = await checkUserMutation.mutateAsync({
        email: userData.email,
      });
      const isNewUser = checkUserResponse?.data?.email?.is_new_user;

      if (isNewUser) {
        toast.info(t("COMMON.TOAST.WELCOME_NEW_USER"));
        routeNewSocialUser(userData);
        return;
      }

      /* `SocialAuthPayload`, not a loose object: `user_type` is `nullable`
         in the endpoint's rules and `null` is how "let the backend decide"
         travels, which the named type records. */
      const finalUserData: SocialAuthPayload = {
        ...userData,
        /* `userType` arrives from `?user_type=` in the URL, so it is an
           arbitrary string until it is parsed. `social-auth` validates it
           with `Rule::in(UserType::selfRegisterableValues())`, and an
           unrecognised value would 422 the sign-in rather than be ignored —
           the same boundary bug `asOtpType` fixed for `?otp_type=`.
           Unparseable falls back to `volunteer`, which is the endpoint's own
           default for a social sign-up. */
        user_type: isModal
          ? asSelfRegisterableUserType(userType) ?? "volunteer"
          : null,
        social_media_provider: "google",
      };

      const response = await passSocialInfoMutation.mutateAsync(finalUserData);
      /* The same reader as the password path above, so the two cannot
         disagree about the envelope again. */
      const userDataToStore = userFromAuthResponse(response);
      if (!userDataToStore) {
        toast.error(t("COMMON.TOAST.LOGIN_FAILED"));
        return;
      }
      setUser(userDataToStore);
      toast.success(t("COMMON.TOAST.LOGIN_SUCCESSFUL"));
      if (isModal) {
        onClose?.();
      } else {
        router.push(returnTo);
      }
    } catch (err) {
      // social-auth rejects an email that already has a password account, and
      // a new volunteer without civil_id — both only make sense to the user as
      // the message the API sent.
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.REGISTRATION_FAILED"));
      }
    }
  };

  /**
   * Signing in with an email and password reports itself inside the submit
   * button. The social path keeps the overlay: it hands the tab to Google, so
   * the whole page really is blocked while it resolves.
   */
  const isSocialLoading =
    checkUserMutation.isPending ||
    passSocialInfoMutation.isPending;

  const isLoading = loginMutation.isPending || isSocialLoading;

  return {
    router,
    setUser,
    selectedLanguage,
    initialFormValues,
    validationSchema,
    loginMutation,
    checkUserMutation,
    passSocialInfoMutation,
    handleSubmit,
    routeNewSocialUser,
    googleLogin,
    isSocialLoading,
    isLoading,
  };
}
