import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useChains, useWalletConnector, useMediaQuery, useConfig } from "@orderly.network/hooks";
import { NetworkImage } from "../../../icon";
import { ArrowLeftRight } from "lucide-react";
import { modal } from "../../../modal";
import { ChainDialog } from "./chainDialog";
import { Spinner } from "../../../spinner";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu";
import { ChainCell } from "./chainCell";
import { MEDIA_TABLET } from "@orderly.network/types";
export const ChainSelect = (props)=>{
    const isTable = useMediaQuery(MEDIA_TABLET);
    const networkId = useConfig("networkId");
    const [allChains, { findByChainId }] = useChains(undefined, {
        pick: "network_infos",
        filter: (chain)=>chain.network_infos?.bridge_enable || chain.network_infos?.bridgeless
    });
    const { connectedChain } = useWalletConnector();
    const chains = useMemo(()=>{
        let targetChains = allChains;
        if (props.chains) {
            targetChains.mainnet = props.chains.mainnet?.map((item)=>item.network_infos);
            targetChains.testnet = props.chains.testnet?.map((item)=>item.network_infos);
        }
        if (Array.isArray(targetChains)) return targetChains;
        if (targetChains === undefined) return [];
        return targetChains[networkId];
    }, [
        allChains,
        props.chains,
        networkId
    ]);
    const { value } = props;
    const currentChain = useMemo(()=>{
        if (!value || !chains || !Array.isArray(chains)) return undefined;
        if (chains.findIndex(// @ts-ignore
        (chain)=>chain.chain_id === value.id) < 0) {
            return undefined;
        }
        return value.info?.network_infos;
    }, [
        value,
        chains
    ]);
    const onChainChange = (chainId)=>{
        if (!chainId) return;
        let chainInfo;
        if (props.chains) {
            chainInfo = [
                ...props.chains?.mainnet,
                ...props.chains?.testnet
            ].find(// @ts-ignore
            (item)=>parseInt(item.network_infos?.chain_id) === parseInt(chainId));
        } else {
            chainInfo = findByChainId(chainId);
        }
        chainInfo && props?.onValueChange?.(chainInfo);
    };
    const onClick = useCallback(async ()=>{
        const result = await modal.show(ChainDialog, {
            mainChains: chains,
            currentChainId: value?.id
        });
        onChainChange(result?.id);
    }, [
        chains,
        value?.id,
        props.onValueChange,
        findByChainId,
        props.chains
    ]);
    const onDropMenuItemClick = useCallback((chain)=>{
        onChainChange(chain.chain_id);
    }, [
        props?.onValueChange,
        findByChainId,
        props.chains
    ]);
    useEffect(()=>{
        if (!!chains || !!props.chains) {
            let chainInfo;
            if (props.chains) {
                chainInfo = [
                    ...props.chains?.mainnet,
                    ...props.chains?.testnet
                ].find(// @ts-ignore
                (item)=>// @ts-ignore
                    parseInt(item.network_infos?.chain_id) === // @ts-ignore
                    parseInt(props.value?.id));
            } else {
                chainInfo = findByChainId(props.value?.id);
            }
            if (!chainInfo) return;
            props.onChainInited?.(chainInfo);
        }
    }, [
        props.value?.id,
        chains?.length,
        props.chains
    ]);
    // if chains is unknown, always can select chains
    const selectable = (!currentChain || chains?.length > 1) && !props.settingChain;
    const icon = useMemo(()=>{
        if (props.settingChain) {
            return /*#__PURE__*/ _jsx(Spinner, {
                size: "small",
                className: "orderly-text-primary-light"
            });
        }
        // if chains is unknown, always show icon
        if (!currentChain || chains?.length > 1) {
            return(// @ts-ignore
            /*#__PURE__*/ _jsx(ArrowLeftRight, {
                size: 16,
                className: "orderly-text-primary-light"
            }));
        }
        return null;
    }, [
        chains?.length,
        props.settingChain,
        currentChain
    ]);
    if (isTable) {
        return /*#__PURE__*/ _jsx(MobileChainSelect, {
            chains: chains,
            onClick: onClick,
            currentChain: currentChain,
            icon: icon,
            selectable: selectable
        });
    }
    return /*#__PURE__*/ _jsx(DesktopChainSelect, {
        chains: chains,
        currentChain: currentChain,
        icon: icon,
        connectedChain: connectedChain,
        onDropMenuItemClick: onDropMenuItemClick,
        selectable: selectable
    });
};
const MobileChainSelect = (props)=>{
    const { onClick, currentChain, icon } = props;
    return /*#__PURE__*/ _jsxs("button", {
        className: "orderly-flex orderly-w-full orderly-items-center orderly-px-2 orderly-rounded orderly-bg-base-500",
        disabled: !props.selectable,
        onClick: onClick,
        children: [
            /*#__PURE__*/ _jsx(NetworkImage, {
                id: currentChain?.chain_id,
                type: currentChain ? "chain" : "unknown",
                size: "small",
                rounded: true
            }),
            /*#__PURE__*/ _jsx("span", {
                className: "orderly-flex-1 orderly-px-2 orderly-text-3xs orderly-text-left desktop:orderly-text-xs",
                children: currentChain?.name ?? "Unknown"
            }),
            icon
        ]
    });
};
const DesktopChainSelect = (props)=>{
    const { chains, currentChain, icon, connectedChain } = props;
    const [open, setOpen] = useState(false);
    function parseChainId(id) {
        if (typeof id === "number") {
            return id;
        }
        if (typeof id === "string") {
            if (id.startsWith("0x")) {
                return parseInt(id, 16);
            }
            return parseInt(id, 10);
        }
    }
    const buttonElem = useMemo(()=>{
        return /*#__PURE__*/ _jsxs(_Fragment, {
            children: [
                /*#__PURE__*/ _jsx(NetworkImage, {
                    id: currentChain?.chain_id,
                    type: currentChain ? "chain" : "unknown",
                    size: "small",
                    rounded: true
                }),
                /*#__PURE__*/ _jsx("span", {
                    className: "orderly-flex-1 orderly-px-2 orderly-text-3xs orderly-text-left",
                    children: currentChain?.name ?? "Unknown"
                }),
                icon
            ]
        });
    }, [
        currentChain
    ]);
    if (!props.selectable) {
        return /*#__PURE__*/ _jsx("div", {
            className: "orderly-flex orderly-w-full orderly-items-center orderly-px-2 orderly-rounded orderly-bg-base-500",
            children: buttonElem
        });
    }
    return /*#__PURE__*/ _jsxs(DropdownMenu, {
        open: open,
        onOpenChange: setOpen,
        children: [
            /*#__PURE__*/ _jsx(DropdownMenuTrigger, {
                asChild: true,
                children: /*#__PURE__*/ _jsx("button", {
                    className: "orderly-flex orderly-w-full orderly-items-center orderly-px-2 orderly-rounded orderly-bg-base-500",
                    children: buttonElem
                })
            }),
            /*#__PURE__*/ _jsx(DropdownMenuContent, {
                align: "start",
                style: {
                    width: "241px",
                    zIndex: 100
                },
                className: "orderly-rounded-sm orderly-bg-base-700 orderly-max-h-[250px] orderly-overflow-y-auto orderly-overflow-hidden orderly-hide-scrollbar orderly-mt-2 orderly-shadow-[0_4px_4px_0px_rgba(0,0,0,0.25)]",
                children: chains.map((chain, index)=>{
                    return /*#__PURE__*/ _jsx(DropdownMenuItem, {
                        onClick: ()=>{
                            props.onDropMenuItemClick?.(chain);
                        },
                        children: /*#__PURE__*/ _jsx(ChainCell, {
                            name: chain.name,
                            id: chain.chain_id,
                            bridgeless: chain.bridgeless,
                            selected: parseChainId(connectedChain?.id) === chain.chain_id
                        }, chain.chain_id)
                    }, index);
                })
            })
        ]
    });
};

//# sourceMappingURL=chainSelect.js.map