import {
    useCallback,
    useEffect,
    useMemo,
    useState,
} from 'react';

import { rpc } from '@/api/request';
import type { ShmSocialType } from '@/api/types';
import {
    getSocialTypeKey,
    SOCIAL_NETWORK_TYPES,
} from '@/utils/socialAuth';

export const useProfileSocials = () => {
    const [socials, setSocials] = useState<ShmSocialType[]>([]);

    const reloadSocials = useCallback(() => {
        return rpc.socials().then((data) => {
            const result = data?.result ?? [];
            setSocials(result);
            return result;
        });
    }, []);

    useEffect(() => {
        reloadSocials();
    }, [reloadSocials]);

    const linkedTypes = useMemo(
        () => new Set(socials.map(getSocialTypeKey).filter(Boolean)),
        [socials],
    );

    const availableToLink = useMemo(
        () => SOCIAL_NETWORK_TYPES.filter((type) => !linkedTypes.has(type)),
        [linkedTypes],
    );

    return {
        socials,
        reloadSocials,
        availableToLink,
    };
};
