import styles from "./styles.module.scss";
import { useEffect, useRef, useState } from "react";
import SvgIcon from "@components/SvgIcon";
import { useThemeProvider } from "@contexts/themeContext";
import { Popover } from "@mui/material";
import areaCode from "@db/areaCode";
import RadioBtn from "@components/RadioBtn";
import MuiDrawer from "@mui/material/Drawer";
import { localStorageGet, localStorageSet } from "@utils/helpers";
import { LOCAL_DEFAULT_COUNTRY } from "@constants/localkey";
import symbol from "@assets/symbol-defs.svg";
import phoneSvg from '@assets/phone.svg';
const i18n = global.i18n;
const PhoneMaxLengthMap = {
    "1": 10,
}
const getMaxLengthMap = (area) => {
    return PhoneMaxLengthMap[area] || 11;
}
const getDefaultAreaCode = (area) => {
    // let code = "";
    // let defaultCode = localStorageGet(LOCAL_DEFAULT_COUNTRY, "");
    // let first = "";
    // for (let i = 0; i < areaCode.length; i++) {
    //     let item = areaCode[i];
    //     let aCode = item.areaCode;
    //     if (item.areaID === area) {
    //         if (first === "") first = aCode;
    //         if (aCode === defaultCode) {
    //             code = defaultCode;
    //             break;
    //         }
    //     }
    // }
    // if (code === "") code = first;
    // return code;
    return 1;
}
const PhoneInput = ({ innerRef, onChangeCountry, ...props }) => {
    const area = global.getLocalAreaID();
    // const [country, setCountry] = useState("55");
    const [country, setCountry] = useState(getDefaultAreaCode(area));
    const wrapClassName = props.className;
    const message = props.message ? props.message : "";
    props.className = props.inputClass ? props.inputClass : "";
    const [showCountrySelect, setShowCountrySelect] = useState(false);
    const { isMobile } = useThemeProvider();
    const selectRef = useRef(null);
    // const area=useSelector(getArea);
    const [searchValue, setSearchValue] = useState("");
    useEffect(() => {
        onChangeCountry && onChangeCountry(country);
        localStorageSet(LOCAL_DEFAULT_COUNTRY, country);
    }, [country]);
    const onChangeAreaCode = (code) => {
        setCountry(code);
        hideASelect();
    }
    const showASelect = () => {
        setSearchValue("");
        setShowCountrySelect(true);
    }
    const hideASelect = () => {
        setShowCountrySelect(false);
    }
    const getAllAreaCode = () => {
        let list = [];
        for (let i = 0; i < areaCode.length; i++) {
            let item = areaCode[i];
            if (item.areaID === area) {
                let areaCode = item.areaCode;
                let name = item.en.toLowerCase();
                if (searchValue !== "") {
                    let lvalue = searchValue.toLowerCase();
                    if (areaCode.indexOf(lvalue) === -1 && name.indexOf(lvalue) === -1) {
                        continue;
                    }
                }
                if (item.areaCode === country) list.unshift(item);
                else list.push(item);
            }
        }
        return list;
    }
    const renderSearch = () => {
        return (
            <div className={`input-control ${styles.select_search}`}>
                <SvgIcon className={styles.icon} herf={"icon_Search"}></SvgIcon>
                <input onChange={e => setSearchValue(e.target.value)} />
            </div>
        )
    }
    const renderAreaCodeList = () => {
        let list = getAllAreaCode();
        return (
            <div className={styles.select_areacode_con}>
                {
                    list.map((item, index) => {
                        return (
                            <button key={index} className={`${styles.item} ${country === item.areaCode ? styles.active : ''}`} onClick={() => {
                                onChangeAreaCode(item.areaCode)
                            }}>
                                <div className={styles.left}>
                                    <img className={styles.icon} src={item.icon} />
                                    <span className={styles.code}>{"+" + item.areaCode}</span>
                                    <span className={styles.name}>{item.en}</span>
                                </div>
                                <RadioBtn selected={country === item.areaCode} value={item.areaCode} onChange={(value) => {
                                    onChangeAreaCode(item.areaCode)
                                }} />
                            </button>
                        )
                    })
                }
            </div>
        )
    }
    const renderHeader = () => {
        return (
            <div className={styles.header}>
                {i18n.t("areaCodeSelect.title")}
            </div>
        )
    }
    const renderDeskSelect = () => {
        return (
            <Popover
                open={showCountrySelect}
                anchorEl={selectRef.current}
                onClose={() => {
                    hideASelect();
                }}
                anchorOrigin={{
                    vertical: 45,
                    horizontal: 0,
                }}
                sx={{
                    "& .MuiPopover-paper": {
                        backgroundColor: 'var(--widget);',
                        borderRadius: 'var(--border-radius);',
                        width: '25rem;',
                        height: '20rem;',
                        boxShadow: 'var(--widget-shadow);'
                    }
                }}
            >
                <div className={styles.select_con}>
                    {renderSearch()}
                    {renderAreaCodeList()}
                </div>
            </Popover>
        )
    }
    const renderMobileSelect = () => {
        return (
            <MuiDrawer open={showCountrySelect}
                anchor={"bottom"}
                sx={{
                    zIndex: 1300,
                    "& .MuiDrawer-paper": {
                        height: "50%",
                        boxSizing: "border-box",
                        overflow: 'visible !important',
                        backgroundColor: 'var(--widget);',
                        boxShadow: 'var(--widget-shadow);',
                        borderTopLeftRadius: '1rem',
                        borderTopRightRadius: '1rem',
                    },
                }}
                variant="temporary"
                onClose={() => {
                    hideASelect();
                }}>
                <div className={`${styles.select_con} ${styles.select_con_m}`}>
                    {renderHeader()}
                    {renderSearch()}
                    {renderAreaCodeList()}
                </div>
            </MuiDrawer>
        )
    }
    const renderCountrySelect = () => {
        if (isMobile()) return renderMobileSelect();
        else return renderDeskSelect();
    }
    return (
        <>
            <div className={`d-flex flex-column g-6`}>
                <div className={`input-control ${styles.no_focus_border} ${wrapClassName}`}>
                    <div className={styles.l_phone}>
                        <button ref={selectRef} type={"button"} className={styles.country} onClick={() => {
                            //showASelect();
                        }}>
                            <div>{"+" + country}</div>
                            {/* <SvgIcon className={styles.icon} herf={"icon_Arrow"}></SvgIcon> */}
                        </button>
                        <div className={styles.line}></div>
                        <input
                            type="tel"
                            ref={innerRef}
                            maxLength={getMaxLengthMap(country)}
                            {...props}
                        />
                        {/* <SvgIcon className={styles.phone_icon} herf={"icon_Phone"}></SvgIcon> */}
                        {/* <svg className={`${styles.phone_icon}`}>
                            <use xlinkHref={`${symbol}#icon_Phone`} />
                        </svg> */}
                        <svg className={styles.phone_icon}>
                            <use xlinkHref={phoneSvg} />
                        </svg>
                    </div>
                </div>
                {
                    message !== "" ? (<div className="input-prompt-error">{message}</div>) : (<></>)
                }
            </div>
            {/* {renderCountrySelect()} */}
        </>
    )
}

export default PhoneInput

