"use client";

import { useCallback, useEffect, useState } from "react";
import { accountService } from "@/features/account/api/account.api";
import { useAuthStore } from "@/features/auth/stores/auth.store";
import { useProfileEdit } from "./useProfileEdit";
import { useAddressEdit } from "./useAddressEdit";

interface UseProfileDataLoadingOptions {
  /** Initial email from user store */
  email: string;
  /** Initial phone number from user store */
  phonenumber: string;
}

/**
 * Hook that consolidates profile and address data loading.
 * Composes useProfileEdit and useAddressEdit internally.
 */
export function useProfileDataLoading({ email, phonenumber }: UseProfileDataLoadingOptions) {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [reloadKey, setReloadKey] = useState(0);

  const profile = useProfileEdit({
    email,
    phonenumber,
  });

  const address = useAddressEdit({
    address1: "",
    address2: "",
    city: "",
    state: "",
    postcode: "",
    country: "",
    countryCode: "",
    phoneNumber: "",
    phoneCountryCode: "",
  });

  // Extract stable setValue functions to avoid infinite re-render loop.
  // The hook objects (address, profile) are recreated every render, but
  // the setValue callbacks inside them are stable (memoized with useCallback).
  const setAddressValue = address.setValue;
  const setProfileValue = profile.setValue;

  const loadProfile = useCallback(() => {
    void (async () => {
      try {
        setError(null);
        setIsLoading(true);
        const [addr, prof] = await Promise.all([
          accountService.getAddress().catch(() => null),
          accountService.getProfile().catch(() => null),
        ]);
        if (addr) {
          setAddressValue("address1", addr.address1 ?? "");
          setAddressValue("address2", addr.address2 ?? "");
          setAddressValue("city", addr.city ?? "");
          setAddressValue("state", addr.state ?? "");
          setAddressValue("postcode", addr.postcode ?? "");
          setAddressValue("country", addr.country ?? "");
          setAddressValue("countryCode", addr.countryCode ?? "");
          setAddressValue("phoneNumber", addr.phoneNumber ?? "");
          setAddressValue("phoneCountryCode", addr.phoneCountryCode ?? "");
        }
        if (prof) {
          setProfileValue("email", prof.email || "");
          setProfileValue("phonenumber", prof.phonenumber || "");
          // Spread all profile fields into the user state, including sfNumber, dateOfBirth, gender
          useAuthStore.setState(state => ({
            ...state,
            user: state.user
              ? {
                  ...state.user,
                  ...prof,
                }
              : prof,
          }));
        }
      } catch (e) {
        // Keep message customer-safe (no internal details)
        setError(e instanceof Error ? e.message : "Failed to load profile data");
      } finally {
        setIsLoading(false);
      }
    })();
  }, [setAddressValue, setProfileValue]);

  useEffect(() => {
    loadProfile();
  }, [loadProfile, reloadKey]);

  const reload = useCallback(() => {
    setReloadKey(k => k + 1);
  }, []);

  return {
    isLoading,
    error,
    reload,
    profile,
    address,
  };
}
