"use client";

import { useState, useRef, useLayoutEffect } from "react";
import { useRouter } from "next/navigation";
import clsx from "clsx";
import Image from "next/image";
import { useApolloClient } from "@apollo/client/react";
// import { useCustomToast } from "@utils/hooks/useToast";
import { useConfig } from "@utils/hooks/useConfig";
import {switchCurrencyAction} from "@/actions/switchCurrencyAction";
import { overlayLoading } from "@/components/theme/ui/kernel/loading/api";

function getCurrencyFlag(currencyCode: string) {
    let res = '';
    if(currencyCode === "USD") {
        res = "/image/flags/1x1/us.svg";        
    } else if(currencyCode === "GBP") {
        res = "/image/flags/1x1/gb.svg";
    } else if(currencyCode === "CAD") {
        res = "/image/flags/1x1/ca.svg";
    }
    return res;
}
// 使用server action

export function CurrencySwitch() {
    const [showList, setShowList] = useState(false); // 是否显示货币列表
    const [listHeight, setListHeight] = useState(0);
    const buttonRef = useRef<HTMLButtonElement>(null);
    const listRef = useRef<HTMLDivElement>(null);
    const [codeListPosition, setCodeListPosition] = useState({
        top: '0',
        transform: 'translate3d(0, 0%, 0)', 
    });
    const router = useRouter();
    const apolloClient = useApolloClient();
    // 获取货币列表
    const {currencies,getCurrentCurrencyItem} = useConfig();  
    // const {showToast} = useCustomToast();
    const currentCurrency = getCurrentCurrencyItem();
    const currentFlag = getCurrencyFlag(currentCurrency.code);

    const handleCurrencyChange = async (selectCode: string) => {
        if(currentCurrency.code !== selectCode) {
            overlayLoading.start();
            await switchCurrencyAction(selectCode);
            await apolloClient.clearStore(); // 清除apollo缓存
            // showToast('Switch currency successfully.', 'success');
            router.refresh();
            //@todo 暂时先reload
            window.location.reload();
        }
    }

    const buttonClickHandler = () => {
        if(buttonRef.current && !showList) {
            const buttonRect = buttonRef.current?.getBoundingClientRect();
            if(buttonRect.bottom + listHeight > window.innerHeight) { // 显示在上方
                setCodeListPosition({
                    top: '0',
                    transform: 'translate3d(0, -100%, 0)',
                });
            } else { // 显示在下方
                setCodeListPosition({
                    top: `${buttonRect.height}px`,
                    transform: `translate3d(0, 0%, 0)`
                });
            }
        }
        setShowList(!showList);
    };

    useLayoutEffect(() => {
        if (listRef.current && showList) {
            const { height } = listRef.current.getBoundingClientRect();
            setListHeight(height);
            console.log('Measured tooltip height: ' + height);
        }
    }, [showList]);


    return (
        <>
            <div className="relative">
                <button className="flex items-center" ref={buttonRef} onClick={buttonClickHandler}>
                    <Image alt="china flag" width={24} height={24} className="w-6 h-6 mr-2 rounded-xl"
                        src={currentFlag}
                    />
                    <span className="text-ly-12 font-medium">{currentCurrency.code}</span>
                    <svg className="w-4 h-4 ml-2" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4.35366 5.64656L8 9.29289L11.6462 5.6467L11.6465 5.64645C11.6934 5.59956 11.7474 5.56343 11.8087 5.53806C11.8699 5.51269 11.9337 5.5 12 5.5C12.1381 5.5 12.2631 5.55596 12.3535 5.64645C12.4441 5.73693 12.5 5.86193 12.5 6C12.5 6.13807 12.4441 6.26307 12.3535 6.35355L12.3533 6.3538L8.35355 10.3536C8.15829 10.5488 7.84171 10.5488 7.64645 10.3536L3.64645 6.35355C3.55596 6.26307 3.5 6.13807 3.5 6C3.5 5.86193 3.55596 5.73693 3.64645 5.64645C3.73693 5.55596 3.86193 5.5 4 5.5C4.13807 5.5 4.26307 5.55596 4.35355 5.64645L4.35366 5.64656Z" fillRule="evenodd"  fill="#000000" ></path></svg>
                </button>
                <div ref={listRef} className={clsx(
                    "absolute w-37.5 bg-white ly-thin-shadow border border-ly-gray rounded-md z-1",
                    showList ? "block" : "hidden"
                )}
                    onClick={(e) => { e.stopPropagation(); }}
                    style={codeListPosition}
                >
                    {currencies.map((item) => {
                        return (
                            <div className={clsx("relative w-full h-10 flex items-center px-2")} key={item.code}
                                onClick={() => {
                                    handleCurrencyChange(item.code);
                                }}
                            >
                                <Image alt="china flag" width={24} height={24} className="w-6 h-6 rounded-xl mr-2"
                                    src={getCurrencyFlag(item.code)}
                                />
                                <span className="text-ly-12 font-medium">{item.code}</span>
                                {item.code === currentCurrency.code && (
                                    <svg className="absolute w-6 h-6 top-1/2 right-2 -translate-y-1/2" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11882" width="24" height="24"><path d="M876.981333 262.24a32.021333 32.021333 0 0 0-45.237333 1.194667L422.976 694.464 191.605333 464.288a32 32 0 1 0-45.141333 45.376l252.864 251.562667a31.914667 31.914667 0 0 0 22.570667 9.312c0.554667 0 1.109333-0.138667 1.653333-0.16 0.576 0.032 1.141333 0.16 1.728 0.16 8.469333 0 16.928-3.338667 23.221333-9.984l429.664-453.088a31.968 31.968 0 0 0-1.184-45.226667z" p-id="11883"></path></svg>
                                )}
                            </div>
                        )
                    })}
                    
                </div>
            </div>
        </>
    );
}