'use client'

import { useJoin } from 'agora-rtc-react';
import { useEffect, useState } from 'react';
import { MediaControl } from './view';
import { LocalUserPanel, RemoteUserPanel } from './components';
import { PublicUser } from '../../../types/sessions';

type AgoraProps = {
    sessionId: number;
    secret?: string;
    stopCalling: () => void;
    remoteUser?: PublicUser;
};

export const Agora = ({ sessionId, secret, stopCalling, remoteUser }: AgoraProps) => {
    const [calling, setCalling] = useState(false);
    const [micOn, setMic] = useState(false);
    const [cameraOn, setCamera] = useState(false);

    useEffect(() => {
        setCalling(true);
    }, []);

    useJoin(
        {
            appid: process.env.NEXT_PUBLIC_AGORA_APPID,
            channel: `${sessionId}-${secret}`,
            token: null,
        },
        calling,
    );

    const stop = () => {
        stopCalling();
        setCalling(false);
    };

    return (
        <div className="b-agora__wrap b-agora__wrap__single">
            <RemoteUserPanel calling={calling} user={remoteUser} />
            <div className="b-agora__panel">
                <MediaControl
                    calling={calling}
                    cameraOn={cameraOn}
                    micOn={micOn}
                    setCalling={stop}
                    setCamera={() => setCamera(a => !a)}
                    setMic={() => setMic(a => !a)}
                />
                <LocalUserPanel
                    calling={calling}
                    cameraOn={cameraOn}
                    micOn={micOn}
                />
            </div>
        </div>
    );
};
