import { Call } from "@/app/components/Call/Call";
import { createContext, useState } from "react";


export interface CallContextValue {
    call: (callable: string) => void;
    close: () => void;
    activeCall: string;
    callState: CallState;
    muted: boolean;
    sound: boolean;
    setMuted: (muted: boolean) => void;
    setSound: (sound: boolean) => void;
    duration: number;
    setShowCallView: (show: boolean) => void;
}

export enum CallState {
    CONNECTING,
    ACTIVE,
    ENDED,
    INCOMING
}

export const CallContext = createContext<CallContextValue | null>(null);
export interface CallProviderProps {
    children: React.ReactNode;
}

export function CallProvider(props : CallProviderProps) {
    const [activeCall, setActiveCall] = useState<string>("");
    const [callState, setCallState] = useState<CallState>(CallState.ENDED);
    const [muted, setMuted] = useState<boolean>(false);
    const [sound, setSound] = useState<boolean>(true);
    const [duration, setDuration] = useState<number>(0);
    const [showCallView, setShowCallView] = useState<boolean>(callState == CallState.INCOMING);

    const call = (dialog: string) => {
        setActiveCall(dialog);
        setCallState(CallState.CONNECTING);
        setShowCallView(true);
    }

    const close = () => {
        setActiveCall("");
        setCallState(CallState.ENDED);
        setShowCallView(false);
        setDuration(0);
    }

    const context = { 
        call, 
        close, 
        activeCall, 
        callState, 
        muted, 
        sound,
        setMuted,
        setSound,
        duration,
        setShowCallView
    };

    return (
        <CallContext.Provider value={context}>
            {props.children}
            {showCallView && <Call context={context}></Call>}
        </CallContext.Provider> 
    )
}