'use client'

import React, { useState, useEffect } from 'react';
import { SessionType } from '../../../types/sessions';
import { AUTH_USER } from '../../../constants/common';
import { useLocalStorage } from '../../../hooks/useLocalStorage';
import { Loader } from '../../view/Loader';
import { useSessionDetails } from "../../../actions/hooks/useSessionDetails";
import { AgoraClient } from '../agora';
import { AccountMenu } from '../AccountMenu';
import { SessionDetailsContent } from './SessionDetailsContent';
import { useSessionTracking } from '../../../actions/hooks/useSessionTracking';

type SessionDetailsProps = {
    locale: string;
    sessionId: number;
    activeType: SessionType;
};

export const SessionDetails = ({ sessionId, locale, activeType }: SessionDetailsProps) => {
    const { session, errorData, loading, fetchData } = useSessionDetails(locale, sessionId);
    const tracking = useSessionTracking(locale, sessionId);
    const [isCalling, setIsCalling] = useState<boolean>(false);
    const [userData] = useLocalStorage(AUTH_USER, '');
    const { id: userId = 0 } = userData ? JSON.parse(userData) : {};

    const client = session?.clients?.length ? session?.clients[0] : null;
    const isCoach = +userId !== client?.id;

    useEffect(() => {
        if (isCalling) {
            tracking.start();
        } else {
            tracking.stop();
        }
    }, [isCalling]);

    const stopCalling = () => {
        setIsCalling(false);
        fetchData()
    }

    return isCalling
        ? (
            <AgoraClient
                session={session}
                stopCalling={stopCalling}
                isCoach={isCoach}
            />
        ) : (
            <>
                <div className="col-xl-3 col-lg-4 d-none d-lg-block">
                    <AccountMenu locale={locale} />
                </div>
                <div className="col-xl-9 col-lg-8 ">
                    <div className="page-account__inner">
                        <Loader
                            isLoading={loading}
                            errorData={errorData}
                            refresh={fetchData}
                        >
                            {session && (
                                <SessionDetailsContent
                                    locale={locale}
                                    session={session}
                                    activeType={activeType}
                                    startSession={() => setIsCalling(true)}
                                    refresh={fetchData}
                                    isCoach={isCoach}
                                />
                            )}
                        </Loader>
                    </div>
                </div>
            </>
        );
};
