/** @format */

import React, { useCallback, useEffect, useState } from 'react';
import ModalPhoneNumpadStyle, { NumberButton, Input } from './style';
import numbers from '../../lib/numbers';
import CallIcon from '@mui/icons-material/Call';
import { toast } from 'react-hot-toast';
import DropDown from '../DropDown';
import { CommentsDisabledOutlined } from '@mui/icons-material';
import CallHistoryInputDropdown from '../CallHistoryInputDropdown';
import KeyboardControlKeyIcon from '@mui/icons-material/KeyboardControlKey';
import { Text, useTranslator } from '@eo-locale/react';
import SettingsIcon from '@mui/icons-material/Settings';
import { useColorConfig } from '../../storage/globalColorConfig';

const ModalPhoneNumpad = ({
	phoneModal,
	modalState,
	reasons,
	reason,
	onSetDnd,
	dynamicValue,
	position,
	variant,
	extnums,
	setSettingHidden,
	settingHidden,
}) => {
	const boxDialer = window.BoxDialer;

	const useColorConfigStore = useColorConfig((store) => store);
	const [inputValue, setInputValue] = useState('');
	const [call_history, setCall_history] = useState([]);
	const [numberSelectHistory, setNumberSelectHistory] = useState(0);
	const [exNum, setExNum] = useState();
	const translator = useTranslator();

	useEffect(() => {
		let currentCalls = localStorage.getItem('callhistory')
			? JSON.parse(localStorage.getItem('callhistory'))
			: false;
		if (currentCalls) {
			setCall_history(currentCalls);
		}
	}, [localStorage.getItem('callhistory'), inputValue]);

	useEffect(() => {
		if (!modalState.bool) setInputValue('');
	}, [modalState.bool]);

	useEffect(() => {
		if (!phoneModal) setSettingHidden(false);
	}, [phoneModal]);

	const inputController = ({ value, type, from }) => {
		boxDialer.onSoundType({ type: 'pick', bool: true });
		switch (type) {
			case 'add':
				if (
					value.match(/^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g).join('').length
				) {
					if (from === 'input') return setInputValue(value);
					if (from === 'button') setInputValue(inputValue + value);
				}

				break;
			case 'delete':
				if (from === 'button') {
					setInputValue(
						inputValue
							.split('')
							.slice(0, inputValue.length - 1)
							.join(''),
					);
				}
				if (from === 'input') {
					setInputValue(value);
				}
				break;
			default:
				break;
		}
	};

	const history = ({ type }) => {
		if (phoneModal && (modalState.bool ? false : true)) {
			if (
				(type === 'up' && numberSelectHistory < call_history.length) ||
				numberSelectHistory === 'zero'
			) {
				setNumberSelectHistory(
					numberSelectHistory !== 'zero' ? numberSelectHistory + 1 : 0 + 1,
				);
			}
			if (type === 'down' && numberSelectHistory > 0) {
				setNumberSelectHistory(
					numberSelectHistory !== 'zero' ? numberSelectHistory - 1 : 0 - 1,
				);
			}
		}
	};

	useEffect(() => {
		if (phoneModal && (modalState.bool ? false : true)) {
			let selectedNumber;
			if (numberSelectHistory == 0) {
				setInputValue('');
			}
			selectedNumber = call_history.slice(numberSelectHistory * -1)[0]
				? call_history.slice(numberSelectHistory * -1)[0]
				: false;

			if (numberSelectHistory === 0) {
				selectedNumber = '';
				setNumberSelectHistory('zero');
			}
			if (numberSelectHistory === 'zero') {
				selectedNumber = '';
				setNumberSelectHistory('zero');
			}
			if (selectedNumber) {
				setInputValue(selectedNumber.value);
			}
		}
	}, [numberSelectHistory]);

	document.onkeydown = function (e) {
		if (phoneModal && modalState.bool ? false : true) {
			e = e || window.event;
			let actualKeyCode = e.keyCode;
			if (e.ctrlKey && actualKeyCode === 86) {
				navigator.clipboard
					.readText()
					.then((text) => {
						inputController({ type: 'add', value: text, from: 'button' });
					})
					.catch((err) => {
						console.log('Something went wrong', err);
					});
			}
			return true;
		}
	};
	const gameState = {
		toggleCP: (e) => {
			if (phoneModal && (modalState.bool ? false : true) && e.key === 'Enter') {
				callButton();
			} else if (
				phoneModal &&
				(modalState.bool ? false : true) &&
				e.key === 'Backspace'
			) {
				inputController({ type: 'delete', from: 'button', value: e.value });
			} else if (
				phoneModal &&
				(modalState.bool ? false : true) &&
				!isNaN(+e.key)
			) {
				inputController({ type: 'add', value: e.key, from: 'button' });
			} else if (
				phoneModal &&
				(modalState.bool ? false : true) &&
				e.key === 'Backspace'
			) {
			} else if (
				(phoneModal && (modalState.bool ? false : true) && e.keyCode == 38) ||
				e.keyCode == 40
			)
				history({ type: e.keyCode === 38 ? 'up' : 'down' });
		},
	};

	const handleKeyUp = useCallback(
		(event) => {
			gameState.toggleCP(event);
		},
		[gameState.toggleCP],
	);

	useEffect(() => {
		document.addEventListener('keyup', handleKeyUp);

		return () => {
			document.removeEventListener('keyup', handleKeyUp);
		};
	}, [handleKeyUp]);
	// `${Data.getHours()}:${Data.getMinutes()} ${Data.getDate()}.${Data.getMonth()+1}.${Data.getFullYear()}`
	const callButton = () => {

		var currentTime = new Date();
		if (dynamicValue === 'connected') {
			if (
				Boolean(inputValue.toString().length) &&
				call_history.slice(-1)[0]?.value != inputValue
			) {
				let newCallsStringify = JSON.stringify([
					...call_history, {
						value: inputValue,
						time: `${currentTime.getHours()}:${currentTime.getMinutes()} ${currentTime.getDate()}.${currentTime.getMonth()}.${currentTime.getFullYear()}`,
					},
				]);
				localStorage.setItem('callhistory', newCallsStringify);
			}
			boxDialer.initialized(inputValue);
			setInputValue('');
		} else {
			toast.error('Please wait', {
				style: {
					zIndex: '99999999999999999',
				},
			});
		}
		
	};
	const selectFunc = (e) => {
		setInputValue(e);
	};
	const setDefaultHistoryNumberHistory = () => {
		setNumberSelectHistory('zero');
	};

	document.querySelector('body').addEventListener('click', function (e) {
		if (exNum) setExNum(false);
	});
	return (
		<ModalPhoneNumpadStyle
			switchAnim={useColorConfigStore.state?.switchAnim}
			position={position}
			hiddenValue={!phoneModal}
			variant={variant}
			onClick={(e) => e.stopPropagation()}>
			<SettingsIcon
				className={'settingIcon'}
				onClick={() => setSettingHidden(!settingHidden)}
			/>
			<ModalPhoneNumpadStyle.InputArea>
				<CallHistoryInputDropdown
					call_history={call_history}
					inputValue={inputValue}
					selectFunc={selectFunc}
					numberSelectHistory={numberSelectHistory}
					setDefaultHistoryNumberHistory={setDefaultHistoryNumberHistory}
				/>
				{inputValue?.length ? (
					<Input.BackSpaceIcon
						onClick={() => inputController({ type: 'delete', from: 'button' })}
					/>
				) : (
					''
				)}
			</ModalPhoneNumpadStyle.InputArea>
			<ModalPhoneNumpadStyle.ButtonArea>
				{numbers?.map((mapItem) => (
					<NumberButton
						switchAnim={useColorConfigStore.state?.switchAnim}
						sizeContext={useColorConfigStore.state.sizePixel}
						onMouseDown={() =>
							boxDialer.dialTone(mapItem.ringHz[0], mapItem.ringHz[1])
						}
						onMouseUp={() => boxDialer.stop()}
						onMouseOut={() => boxDialer.stop()}
						className='nocopy'
						key={mapItem.id}
						onClick={() => {
							mapItem.type === 'number' &&
								inputController({
									value: mapItem.value,
									type: 'add',
									from: 'button',
								});
						}}>
						{mapItem.nameNumber}
						<NumberButton.Icon>{mapItem.icon}</NumberButton.Icon>
					</NumberButton>
				))}
				{!modalState.bool ? (
					<>
						<NumberButton
							style={{ gridColumn: '1/4' }}
							status={dynamicValue}
							type={'call_button'}>
							<NumberButton.CallButton exNum={exNum}>
								<div className='left' onClick={() => callButton()}>
									<CallIcon className='callIcon' />
									<p className='call_text'>{translator.translate('CALL')}</p>
								</div>
								<div className='right' onClick={() => setExNum(!exNum)}>
									<div className='icon'></div>
								</div>
							</NumberButton.CallButton>
							<NumberButton.CallButtonModal
								switchAnim={useColorConfigStore.state?.switchAnim}
								visiblevalue={exNum}>
								<NumberButton.CallButtonModalInset
									switchAnim={useColorConfigStore.state?.switchAnim}>
									{extnums?.map(({ number, title }, index) => (
										<p
											key={index}
											className='num_item'
											onClick={() => {
												boxDialer.extnum = number;
												setExNum(false);
												callButton();
											}}>
											{title}
										</p>
									))}
								</NumberButton.CallButtonModalInset>
							</NumberButton.CallButtonModal>
						</NumberButton>
					</>
				) : (
					<>
						<div style={{ height: '33px' }}></div>
						<div style={{ height: '33px' }}></div>
					</>
				)}
				<DropDown selectFunc={onSetDnd} reasons={reasons} reason={reason} />
			</ModalPhoneNumpadStyle.ButtonArea>
		</ModalPhoneNumpadStyle>
	);
};

export default ModalPhoneNumpad;
