"use client";

import React,{useState, useLayoutEffect, useRef, useMemo} from "react";
import Image from "next/image";
import clsx from "clsx";
import {
    COUNTRY_PHONECODE,
    formatFinalPhoneValue,
    getPhoneCodeBycountryCode,
    getCountryCodeByPhoneCode
} from "./phoneCodeMetaData";
import { IS_VALID_PHONECODE } from "@utils/constants";

function parsePhoneValue(value: string|undefined) {
    const DEFAULT_PHONE_CODE = "+1";
    const regPhoneCode = IS_VALID_PHONECODE;
    
    let code = DEFAULT_PHONE_CODE;
    let phone = '';
    if(value) {
        const codePart = regPhoneCode.exec(value);
        if(codePart) {
            code = codePart[0].trim() || DEFAULT_PHONE_CODE;
            phone = value.replace(codePart[0], '');
        } else {
            phone = value;
        }

    }
   
    return {
        phoneCode: code,
        phoneNumber: phone
    }
}
/**
 * 受控组件
 */
interface PhoneNumberInputProps {
    // 用于react-hook-form时，推荐使用useForm的 defaultValues 对整个表单设置默认值
    value?: string;
    placeholder: string;
    // 用于react-hook-form时，React 事件处理器类型定义中的“双变（bivariance）”特性 和返回值void的兼容性，使typescript没有提示类型错误
    onChange: (e: string) => void;
    onBlur: (e: string) => void;
    name: string;
    error?: string;
    ref?: React.Ref<HTMLInputElement>;
    countryCode: string;//父组件表单国家字段
    onHasUserSelectedPhoneCode: () => void;
    hasUserSelectedPhoneCode: boolean;
}
function PhoneNumberInput({
    value,
    placeholder,
    onChange,
    onBlur,
    name,
    error,
    ref,
    countryCode,
    onHasUserSelectedPhoneCode,
    hasUserSelectedPhoneCode
}: PhoneNumberInputProps) {
    // const DEFAULT_COUNTRY_CODE = "US";
    const phoneCodeList = COUNTRY_PHONECODE;

    const { phoneCode, phoneNumber } = useMemo(() => {
        return parsePhoneValue(value);
    }, [value]);


    const [selectedPhoneCode, setSelectedPhoneCode] = useState<string | null>(phoneCode);
    const [selectedCountryForPhoneCode, setSelectedCountryForPhoneCode] = useState<string | null>(() => {
        return getCountryCodeByPhoneCode(phoneCode);
    });
    
    const displayPhonecode = useMemo(() => {
        return selectedPhoneCode ?? getPhoneCodeBycountryCode(countryCode);
    },[selectedPhoneCode,countryCode]);
    const displayCountryCode = useMemo(() => {
        return selectedCountryForPhoneCode ?? countryCode;
    }, [selectedCountryForPhoneCode,countryCode]);

    ////////////////////////////////
    const rootRef = useRef<HTMLDivElement>(null);
    const [rootBounding, setRootBounding] = useState<{
        top: number;
        bottom: number;
        left: number;
        right: number;
        width: number;
        height: number;
    }|null>(null);
    const codeListRef = useRef<HTMLDivElement>(null);
    const [codeListHeight, setCodeListHeight] = useState(0); 
    const [showCodeList, setShowCodeList] = useState(false);

    useLayoutEffect(() => {
        if (codeListRef.current && showCodeList) {
            const { height } = codeListRef.current.getBoundingClientRect();
            setCodeListHeight(height);
            console.log('Measured tooltip height: ' + height);
        }
    }, [showCodeList]);
    let style = {
        top: '0',
        transform: 'translate3d(0, 0, 0)'
    };
    if(rootBounding !== null) {
        if(rootBounding.bottom + codeListHeight > window.innerHeight) { // 显示在上方
            style = {
                top: '-1px',
                transform: 'translate3d(0, -100%, 0)',
            };
        } else { // 显示在下方
            style = {
                top: `${rootBounding.height}px`,
                transform: `translate3d(0, 0%, 0)`
            };
        }
    }

    const handleShowCodeList = () => { 
        const rootRect = rootRef.current?.getBoundingClientRect();
        if(rootRect) {
            setRootBounding({
                top: rootRect?.top,
                left: rootRect?.left,
                width: rootRect?.width,
                height: rootRect?.height,
                bottom: rootRect?.bottom,
                right: rootRect?.right,
            });
        }
        setShowCodeList(!showCodeList);
    };
    ///////////////////////////

    const phoneCodeSelect = (pCode: string, ccode: string) => {
        onChange(formatFinalPhoneValue(pCode, phoneNumber));
        setSelectedPhoneCode(pCode);
        setSelectedCountryForPhoneCode(ccode);
        
        if(!hasUserSelectedPhoneCode) {
            onHasUserSelectedPhoneCode(); // 标记为用户手动选择过
        }
        setShowCodeList(false);
    };

    const phoneNumberChange = (value: string) => {

        onChange(formatFinalPhoneValue(phoneCode, value));

    };
    const phoneNumberBlur = (value: string) => {
        onBlur(formatFinalPhoneValue(phoneCode, value));

    };
    // const phoneNumberInput = (value: string) => {
    //     setPhoneNumber(value);
    // };

    return (
        <div className="w-full relative" ref={rootRef}>
            <input type="hidden" 
                name={name}
                value={value}
                ref={ref}
            />
            <div className="flex gap-4 box-border border-1 border-ly-inputborder">
                <div className="flex-auto px-3.75" onClick={handleShowCodeList}>
                    <div className="h-11.5 text-ly-12 flex items-center">
                        
                        <Image alt="china flag" width={24} height={18} className="w-6 h-4.5 mr-2"
                            src={`/image/flags/4x3/${displayCountryCode.toLowerCase()}.svg`}
                        />
                        {/* {phoneCode} */}
                        {displayPhonecode}
                    </div>
                </div>
                
                <input className="flex-auto h-11.5 pr-3 placeholder:text-ly-placeholder text-ly-12 focus:outline-none" 
                    value={phoneNumber}
                    type="text"
                    placeholder={placeholder}
                    onChange={(e) => phoneNumberChange(e.target.value)}
                    onBlur={(e) => phoneNumberBlur(e.target.value)}
                />

            </div>
            {error && <p className="text-red-500 text-ly-12">{error}</p>}
            <div ref={codeListRef} className={clsx(
                    'absolute w-full left-0 top-0 h-50 overflow-y-scroll z-10 bg-white',
                    {
                        "hidden": !showCodeList
                    },
                )}
                style={style}
            >
                <ul>
                    {phoneCodeList.map((item) => {
                        return (<li className="text-ly-12 flex items-center h-8 gap-2" key={item.code} 
                            onClick={() => {
                                phoneCodeSelect(item.phoneCode, item.code);
                                // phoneCodeChange(item.code);
                            }}
                        >
                            <Image alt="china flag" width={20} height={15} className="w-5 h-3.75"
                                src={`/image/flags/4x3/${item.code.toLowerCase()}.svg`}
                            /> {item.phoneCode} {item.name}
                        </li>);

                    })}
                </ul>
            </div>
        </div> 
    );
}
// 设置 displayName，便于调试
PhoneNumberInput.displayName = 'PhoneNumberInput';

export default PhoneNumberInput;