/** @format */

import React, { useContext, useEffect, useState } from 'react';
import packageJson from '../../package.json';
import DefaultWidjetUi from '../components/DefaultWidjetUi';
import ModalPhoneNumpad from '../components/ModalPhoneNumpad';
import Modal from '../components/Modal';
import BxMiniWidjetUi from '../components/BxMiniWidjetUi';
import SecondNotifSip from '../components/SecondNotifSip';
import InnerCaller from '../components/InnerCaller';
import { useConfigHoldMute } from "../storage"
import SettingComponent from "../components/setting"
import { useColorConfig } from "../storage/globalColorConfig"

const Root = ({ wsphonedata, onSetDnd, setWsphonedata, callMethod }) => {
    const boxDialer = window.BoxDialer;
    const useColorConfigStore = useColorConfig((store) => store)
    const configHoldMute = useConfigHoldMute((state) => state)
    const [phoneModal, setPhoneModal] = useState(false);
    const [dynamicValue, setDynamicValue] = useState('pending');
    const [modalState, setModalState] = useState(false);
    const [settingHidden, setSettingHidden] = useState(false);
    const [secondLine, setSecondLine] = useState(false);
    // const [secondLine, setSecondLine] = useState(false);
    const [innerTimer, setInnerTimer] = useState(null);
    const [innerCallerModal, setInnerCallerModal] = useState({
        bool: false, type: null, from: '',
    });

    useEffect(() => {
        if (secondLine) {
            setTimeout(() => {
                setSecondLine(false);
            }, 5000);
        }
    }, [secondLine]);

    useEffect(() => {
        boxDialer.setGlobalHistoryData(useColorConfigStore.state)
    }, [useColorConfigStore.state])

    useEffect(() => {
        if (wsphonedata && wsphonedata?.number) {
            boxDialer.setSipStateChangeCallback(setDynamicValue, 'dynamicValue');
            boxDialer.setSipStateChangeCallback(setModalState, 'modalState');
            boxDialer.setSipStateChangeCallback(setSecondLine, 'secondLine');
            boxDialer.setSipStateChangeCallback(setPhoneModal, 'phoneModal');
            boxDialer.setSipStateChangeCallback(setInnerTimer, 'innerTimer');
            boxDialer.setSipStateChangeCallback(configHoldMute.setState, 'setCallEvents');
            boxDialer.setSipStateChangeCallback(setInnerCallerModal, 'innerCallerModal',);

            if (boxDialer.isUaRunning()) console.log('UA is running! in other tab'); else boxDialer.sipRegister(wsphonedata);

            setTimeout(function waitUaRegisterLost() {
                if (boxDialer.isUaRunning() || boxDialer.isRestarting) setTimeout(waitUaRegisterLost, 10); else boxDialer.sipRegister(wsphonedata);
            }, 10);
        }
    }, []);

    const hangupButton = () => {
        boxDialer.hangupButtonClick();
    };

    window.setWSData = (result) => {
        console.log('setWsphonedata', result);
        setWsphonedata(result);
    };

    const reasonSelect = async (e) => {
        let result = await onSetDnd(e);
        if (setWsphonedata) {
            setWsphonedata(result);
        }
        console.log('reasonSelect_setWsphonedata', typeof setWsphonedata)
    };

    const getTransferers = async (e) => {
        let result = await callMethod({
            method: 'getPeers',
        });
        setWsphonedata(result);
    };


    // useEffect(()=> {
    //     console.log('auto_answer running: ', modalState.callType === 'incoming' && modalState.bool)
    // }, [modalState.callType, modalState.bool, useColorConfigStore.state?.autoAnswer, useColorConfigStore.state?.autoAnswerSecond])


    const selectWidjetType = (type) => {
        switch (type) {
            case 'bxmini':
                return (<BxMiniWidjetUi
                    widjetState={dynamicValue}
                    phoneNumber={wsphonedata?.number}
                    reason={wsphonedata?.reason}
                    widjetVersion={packageJson?.version}
                    leftTime={wsphonedata.lefttime}
                    position={wsphonedata.position || 'bottomLeft'}
                    onClick={() => {
                        phoneModal ? setPhoneModal(false) : setPhoneModal(true);
                    }}
                />);
            default:
                return (<DefaultWidjetUi
                    widjetState={dynamicValue}
                    phoneNumber={wsphonedata?.number}
                    reason={wsphonedata?.reason}
                    widjetVersion={packageJson?.version}
                    leftTime={wsphonedata.lefttime}
                    position={wsphonedata.position || 'bottomLeft'}
                    onClick={() => {
                        phoneModal ? setPhoneModal(false) : setPhoneModal(true);
                    }}
                />);
        }
    };

    // console.log('wsphonedata_all_data: ', wsphonedata?.position, wsphonedata?.number, wsphonedata,);


    window.onbeforeunload = () => {
        if (typeof BX !== 'undefined') {
            boxDialer.isRestarting = true;
            console.log('window_onbeforeunload =============-------------');
            localStorage.removeItem('mycall');
            localStorage.removeItem(BX.bitrix_sessid() + '_mycall');

            console.log('--==== Checking removed Items: ', localStorage.getItem('mycall'), localStorage.getItem(BX.bitrix_sessid() + '_mycall'),);
        }
    };


    if (!wsphonedata?.number && !wsphonedata?.position) return;
    return (<>
        {selectWidjetType(wsphonedata.variant)}
        <SettingComponent
            settingHidden={settingHidden && phoneModal ? true : false}
            variant={wsphonedata.variant || 'defaultWidjet'}
            position={wsphonedata.position || 'bottomLeft'}
        />

        <ModalPhoneNumpad
            setSettingHidden={setSettingHidden}
            settingHidden={settingHidden}
            modalState={modalState}
            phoneModal={phoneModal}
            reasons={wsphonedata?.reasons}
            reason={wsphonedata?.reason}
            onClick={(e) => e.stopPropagation()}
            dynamicValue={dynamicValue}
            onSetDnd={reasonSelect}
            variant={wsphonedata.variant || 'defaultWidjet'}
            position={wsphonedata.position || 'bottomLeft'}
            extnums={wsphonedata.extnums}
        />

        <Modal
            className='tailwindGlobalCss'
            hidden={modalState.bool}
            callType={modalState.callType}
            // hidden={true}
            // callType={'incoming'}
            hangupButton={hangupButton}
            phoneNumber={modalState.callType === 'outcoming' ? 'inputValue' : modalState.callFromName}
        />

        <InnerCaller
            hidden={innerCallerModal.bool}
            type={innerCallerModal.type}
            from={innerCallerModal.from}
            innerTimer={innerTimer}
        />

        <SecondNotifSip secondLine={secondLine} />
    </>);
};
export default Root;

// ======================================================
// var no_active_delay = 60;
// var now_no_active = 0;
// function activeUser() {
// 	now_no_active = 0;
// }
// function updateChat() {
// 	location.reload();
// 	return;
// }
// setInterval(() => {
// 	if (
// 		now_no_active >= no_active_delay && modalState.bool === 'undefined'
// 			? true
// 			: (!modalState.bool && !innerCallerModal.bool) ||
// 			  modalState.bool === 'undefined'
// 	) {
// 		now_no_active++;
// 		updateChat();
// 	}
// }, 1000);
// document.onmousemove = activeUser;
// console.log(
// 	'modalState_bool: ',
// 	modalState.bool === 'undefined'
// 		? true
// 		: (!modalState.bool && !innerCallerModal.bool) ||
// 				modalState.bool === 'undefined',
// );
// ======================================================
