'use client'

import React, { useState, useEffect } from 'react';
import { RoomsType } from '../../../types/rooms';
import { useSessionTracking } from '../../../actions/hooks/useSessionTracking';
import { AccountMenu } from '../AccountMenu';
import { Loader } from '../../view/Loader';
import { RoomDetailsContent } from './RoomDetailsContent';
import { useRoomDetails } from '../../../actions/hooks/useRoomDetails';
import { AgoraClientGroup } from '../agora';

type RoomDetailsProps = {
    locale: string;
    roomId: number;
    activeType: RoomsType;
};

export const RoomDetails = ({ roomId, locale, activeType }: RoomDetailsProps) => {
    const { room, errorData, loading, fetchData } = useRoomDetails(locale, roomId);
    const tracking = useSessionTracking(locale, roomId);
    const [isCalling, setIsCalling] = useState<boolean>(false);

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

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

    return isCalling
        ? (
            <AgoraClientGroup
                room={room}
                stopCalling={stopCalling}
            />
        ) : (
            <>
                <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}
                        >
                            <RoomDetailsContent
                                locale={locale}
                                room={room}
                                activeType={activeType}
                                startRoom={() => setIsCalling(true)}
                                refresh={fetchData}
                            />
                        </Loader>
                    </div>
                </div>
            </>
        );
};
