'use client'

import { useCallback, useEffect, useState } from 'react';
import { ProfileData, ProfileRequest } from '../../types/profile';
import { getPersonalData, setPersonData } from '../profile';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY } from '../../constants/common';

export const useProfileSettings = (locale: string) => {
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const [profileSettings, setProfileSettings] = useState<ProfileData | undefined>();
    const [fetchLoading, setFetchLoading] = useState<boolean>(false);

    const fetchProfileSettings = () => {
        if (jwt) {
            getPersonalData(locale, jwt)
                .then((data) => {
                    setProfileSettings(data);
                })
                .catch((err) => {

                })
                .finally(() => {
                    setFetchLoading(false);
                });
        }
    };

    const save = useCallback((data: ProfileRequest) => setPersonData(data, locale, jwt), []);

    return {
        fetchLoading,
        fetchProfileSettings,
        save,
        profileSettings
    };
};
