'use client'

import { useCallback, useEffect, useState } from 'react';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY } from '../../constants/common';
import { Session } from '../../types/sessions';
import { getSessionDetails } from '../sessions';

export const useSessionDetails = (locale: string, sessionId: number) => {
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const [session, setSession] = useState<Session>();
    const [errorData, setErrorData] = useState<any>();
    const [loading, setLoading] = useState<boolean>(false);

    const fetchData = useCallback(() => {
        setLoading(true);
        setErrorData(undefined);
        setSession(undefined);

        getSessionDetails(locale, jwt, sessionId)
            .then(({ data }) => {
                setSession(data);
            })
            .catch((err) => {
                setErrorData(err);
            })
            .finally(() => {
                setLoading(false);
            })
    }, []);

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

    return {
        fetchData,
        loading,
        session,
        errorData
    };
};
