"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { checkUserRequest } from "@/features/auth/services/authApi";
import { getAccountInfo, getVolunteerProfile, updateAccountInfo, updateVolunteerProfile } from "@/features/profile/services/profileApi";
import { getDefaultProfileImage } from "@/lib/helpers";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { asset } from "./volunteerAccountConstants";
import { useVolunteerAccountOptions } from "./useVolunteerAccountOptions";
import { useProfilePictureUpload } from "./useProfilePictureUpload";
import { useNicknameAvailability } from "./useNicknameAvailability";
import { isApiSuccess } from "@/lib/api/errors";
import { useVolunteerAccountSubmit } from "./useVolunteerAccountSubmit";
import { buildVolunteerAccountInitialValues } from "./volunteerAccountInitialValues";
import { buildVolunteerAccountValidation } from "./volunteerAccountValidation";

/**
 * Everything the volunteer account screen needs, assembled.
 *
 * It reads two records and saves their editable fields atomically, and wires together
 * eight pieces: both records' queries, the five dropdown sources, the avatar
 * upload (saved on its own), the debounced nickname check, the merged initial
 * values, the conditional validation, and the fan-out save. Assembling them here
 * leaves the component as markup.
 */
export function useVolunteerAccountForm() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const updateProfilePic = useAuthStore((s) => s.updateProfilePic);
  const updateUser = useAuthStore((s) => s.updateUser);
  const authToken = user?.auth_token;
  const selectedLanguage = useLanguageStore((s) => s.language);

  const [componentKey, setComponentKey] = useState(0);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [profilePic, setProfilePic] = useState<string | null>(null);
  const [isProfilePicUpdating, setIsProfilePicUpdating] = useState(false);
  const [isOnlyProfilePicChanged, setIsOnlyProfilePicChanged] = useState(false);

  // Username availability check states

  // States for image cropping
  const [showCropModal, setShowCropModal] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  const updateAccountMutation = useMutation({ mutationFn: updateAccountInfo });
  const updateProfileMutation = useMutation({
    mutationFn: updateVolunteerProfile,
    onSuccess: async response => {
      if (!isApiSuccess(response)) return;
      queryClient.setQueryData(["volunteer-profile"], response);
      await queryClient.invalidateQueries({ queryKey: ["account-info"] });
    },
  });
  const checkUserMutation = useMutation({ mutationFn: checkUserRequest });

  const isUpdatingAccount = updateAccountMutation.isPending;
  const isUpdatingProfile = updateProfileMutation.isPending;

  const {
    data: accountData,
    isLoading: isAccountLoading,
    error: accountError,
    refetch: refetchAccountData,
  } = useQuery({
    queryKey: ["account-info"],
    queryFn: getAccountInfo,
    enabled: Boolean(authToken),
  });

  const {
    data: volunteerProfile,
    isLoading: isProfileLoading,
    error: profileError,
    refetch: refetchVolunteerProfile,
  } = useQuery({
    queryKey: ["volunteer-profile"],
    queryFn: getVolunteerProfile,
    enabled: Boolean(authToken),
    refetchOnMount: "always",
  });

  const {
    tagsLoading,
    genderData,
    genderLoading,
    relationshipLoading,
    tagOptions,
    genderOptions,
    relationshipOptions,
    nationalityOpts,
    healthConcernOpts,
    occupationOpts,
  } = useVolunteerAccountOptions(selectedLanguage);

  const getDefaultImage = () =>
    getDefaultProfileImage(
      user?.gender_display?.value_en,
      asset("profile/male_profile.svg"),
      asset("profile/female_profile.svg"),
      asset("profile/org_profile.svg")
    );

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

  /*
   * Follow the fetched account during render, not from an effect.
   *
   * `profilePic` is also written by the upload flow (optimistically, before the
   * save returns), so it is not purely derived — but it must re-sync when the
   * account is refetched. The effect version showed the previous avatar for one
   * frame after every refetch.
   */
  // Starts empty, not at `accountData`: when the account is already cached
  // (opening this page from the profile) the first render must sync too, or
  // the avatar stays on the gender fallback until something refetches.
  const [prevAccountData, setPrevAccountData] = useState<typeof accountData>(undefined);
  if (accountData !== prevAccountData) {
    setPrevAccountData(accountData);
    if (accountData?.data?.profile_pic) {
      setProfilePic(accountData.data.profile_pic);
    }
  }

  const initialValues = buildVolunteerAccountInitialValues(
    accountData,
    volunteerProfile
  );

  const { nicknameAvailability, checkNicknameAvailability } =
    useNicknameAvailability({
      checkUserMutation,
      t,
    });

  const validationSchema = buildVolunteerAccountValidation({
    t,
    initialNickname: initialValues.nickname,
    initialDob: volunteerProfile?.data?.dob,
    storedBirthYear: volunteerProfile?.data?.birth_year ?? accountData?.data?.birth_year,
    nicknameAvailable: nicknameAvailability.available,
  });

  const { handleFileChange, handleCropComplete } = useProfilePictureUpload({
    t,
    setUploadError,
    setSelectedImage,
    setShowCropModal,
    setProfilePic,
    setIsProfilePicUpdating,
    setIsOnlyProfilePicChanged,
    setComponentKey,
    updateAccountMutation,
    updateProfilePic,
    router,
  });

  const handleSubmit = useVolunteerAccountSubmit({
    t,
    selectedLanguage,
    user,
    updateUser,
    updateProfilePic,
    volunteerProfile,
    router,
    accountData,
    genderData,
    genderOptions,
    setIsOnlyProfilePicChanged,
    updateAccountMutation,
    updateProfileMutation,
    setComponentKey,
  });

  return {
    t,
    user,
    authToken,
    selectedLanguage,
    componentKey,
    uploadError,
    profilePic,
    isProfilePicUpdating,
    showCropModal,
    setShowCropModal,
    selectedImage,
    setSelectedImage,
    isUpdatingAccount,
    isUpdatingProfile,
    accountData,
    isAccountLoading,
    accountError,
    volunteerProfile,
    isProfileLoading,
    profileError,
    tagsLoading,
    genderLoading,
    relationshipLoading,
    tagOptions,
    genderOptions,
    relationshipOptions,
    nationalityOpts,
    healthConcernOpts,
    occupationOpts,
    getDefaultImage,
    initialValues,
    validationSchema,
    nicknameAvailability,
    checkNicknameAvailability,
    handleFileChange,
    handleCropComplete,
    handleSubmit,
    isOnlyProfilePicChanged,
    router,
  };
}
