"use client";

import { useEffect, useState, useCallback } from "react";
import { useAuthStore } from "@/features/auth/services/auth.store";
import { accountService } from "@/features/account/services/account.service";
import { logger } from "@/lib/logger";

// Use centralized profile types
import type { ProfileEditFormData, Address } from "@customer-portal/domain/customer";

export function useProfileData() {
  const { user } = useAuthStore();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSavingProfile, setIsSavingProfile] = useState(false);
  const [isSavingAddress, setIsSavingAddress] = useState(false);
  const [billingInfo, setBillingInfo] = useState<{ address: Address } | null>(null);

  const [formData, setFormData] = useState<ProfileEditFormData>({
    firstname: user?.firstname || "",
    lastname: user?.lastname || "",
    phonenumber: user?.phonenumber || "",
  });

  const [addressData, setAddress] = useState<Address>({
    address1: "",
    address2: "",
    city: "",
    state: "",
    postcode: "",
    country: "",
    countryCode: "",
    phoneNumber: "",
    phoneCountryCode: "",
  });

  const fetchBillingInfo = useCallback(async () => {
    try {
      setLoading(true);
      const address = await accountService.getAddress().catch(() => null);
      if (address) {
        const normalizedAddress: Address = {
          address1: address.address1 || "",
          address2: address.address2 || "",
          city: address.city || "",
          state: address.state || "",
          postcode: address.postcode || "",
          country: address.country || "",
          countryCode: address.countryCode || "",
          phoneNumber: address.phoneNumber || "",
          phoneCountryCode: address.phoneCountryCode || "",
        };
        setBillingInfo({ address: normalizedAddress });
        setAddress(normalizedAddress);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load address information");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchBillingInfo();
  }, [fetchBillingInfo]);

  useEffect(() => {
    if (user) {
      setFormData({
        firstname: user.firstname || "",
        lastname: user.lastname || "",
        phonenumber: user.phonenumber || "",
      });
    }
  }, [user]);

  const saveProfile = async (next: ProfileEditFormData) => {
    setIsSavingProfile(true);
    try {
      const updatedUser = await accountService.updateProfile({
        firstname: next.firstname,
        lastname: next.lastname,
        phonenumber: next.phonenumber,
      });
      useAuthStore.setState(state => ({
        ...state,
        user: state.user ? { ...state.user, ...updatedUser } : state.user,
      }));
      setFormData(next);
      return true;
    } catch (err) {
      logger.error("Error updating profile", err);
      setError(err instanceof Error ? err.message : "Failed to update profile");
      return false;
    } finally {
      setIsSavingProfile(false);
    }
  };

  const saveAddress = async (next: Address) => {
    setIsSavingAddress(true);
    setError(null);
    try {
      await accountService.updateAddress({
        address1: next.address1,
        address2: next.address2,
        city: next.city,
        state: next.state,
        postcode: next.postcode,
        country: next.country,
        countryCode: next.countryCode,
        phoneNumber: next.phoneNumber,
        phoneCountryCode: next.phoneCountryCode,
      });
      setBillingInfo({ address: next });
      setAddress(next);
      return true;
    } catch (err) {
      logger.error("Error updating address", err);
      setError(err instanceof Error ? err.message : "Failed to update address");
      return false;
    } finally {
      setIsSavingAddress(false);
    }
  };

  return {
    loading,
    error,
    billingInfo,
    formData,
    setFormData,
    addressData,
    setAddressData: setAddress,
    saveProfile,
    saveAddress,
    isSavingProfile,
    isSavingAddress,
  } as const;
}
