import { FunctionComponent, useEffect, useMemo, useState } from "react"
import { MdOutlineNetworkCell, MdOutlineOnlinePrediction } from "react-icons/md"
import { RiGlobalLine } from "react-icons/ri";
import pckg from "../../package.json"
import { FaGithub, FaDiscord, FaTelegramPlane } from "react-icons/fa"
import { FaXTwitter } from "react-icons/fa6";
import * as environment from "../environment"
import { BraveModal, Logo, MenuContent, Bootnodes } from "../components"
import { Link } from "react-router-dom"
import { useActiveChains } from "@/hooks/useActiveChains"
import { NetworkTabProps } from "@/types"
import { NetworkTab } from "./WalletPopup/components"
import { Accordion } from "@/components/ui/accordion"

type MenuItemTypes = "item" | "title" | "icon"

const item = [
    "group",
    "flex",
    "items-center",
    "text-base",
    "text-primary",
    "py-4",
    "px-6",
    "h-12",
    "overflow-hidden",
    "text-ellipsis",
    "whitespace-nowrap",
    "bg-background",
    "md:justify-start",
    "justify-center",
]
const itemInactive = [
    "bg-transparent",
    "transition",
    "duration-300",
    "ease-in-out",
]
const itemActive = [
    "cursor-default",
]

const title = ["ml-4 font-inter font-medium text-primary"]
const titleInactive = ["group-hover:text-accent"]
const titleActive = ["text-accent", "cursor-default"]

const icon = [
    "w-6",
    "h-6",
    "md:w-4",
    "md:h-4",
    "text-primary",
]
const iconInactive = ["group-hover:text-accent"]
const iconActive = ["cursor-default"]

const cName = (type: MenuItemTypes, menu = 0, reqMenu: number) => {
    let classes: string[] = []
    switch (type) {
        case "item":
            if (menu === reqMenu) {
                classes = [...item, ...itemActive]
            } else {
                classes = [...item, ...itemInactive]
            }
            break
        case "title":
            if (menu === reqMenu) {
                classes = [...title, ...titleActive]
            } else {
                classes = [...title, ...titleInactive]
            }
            break
        case "icon":
            if (menu === reqMenu) {
                classes = [...icon, ...iconActive]
            } else {
                classes = [...icon, ...iconInactive]
            }
            break
    }
    return classes.join(" ")
}

const Networks: React.FC = () => {
    const chains = useActiveChains()
    const networks: NetworkTabProps[] = useMemo(
        () =>
        chains.map(({ chainName, isWellKnown, details }) => {
            return {
                isWellKnown,
                name: chainName,
                health: {
                    isSyncing: details[0].isSyncing,
                    peers: details[0].peers,
                    status: "connected",
                    bestBlockHeight: details[0].bestBlockHeight,
                },
                apps: details.map(({ url }) => ({
                    name: url ?? "",
                    url: url,
                })),
            }
        }),
        [chains],
    )

    return (
        <section className="container">
            <h2 className="pb-2 space-y-2 text-3xl font-semibold md:pb-4">
                Networks
            </h2>
            {networks.length ? (
                <Accordion type="multiple" className="w-full flex flex-col gap-4">
                    {networks.map(({ name, health, apps, isWellKnown }, i) => (
                        <NetworkTab
                            key={i}
                            name={name}
                            health={health}
                            isWellKnown={isWellKnown}
                            apps={apps}
                        />
                    ))}
                </Accordion>
            ) : (
                <div>The extension isn't connected to any network.</div>
            )}
        </section>
    )
}

export const Options: FunctionComponent = () => {
    const [menu, setMenu] = useState<0 | 1>(0)
    const [showModal, setShowModal] = useState<boolean>(false)

    useEffect(() => {
        window.navigator?.brave?.isBrave().then(async (isBrave: any) => {
            const braveSetting = await environment.get({ type: "braveSetting" })
            setShowModal(isBrave && !braveSetting)
        })
    }, [])

    return (
        <>
            <BraveModal show={showModal} isOptions={true} />
            <div className="h-full flex">
                <div className="h-[full] bg-muted flex flex-col md:w-[264px] w-60">
                    <div className="md:px-6 md:pt-5 md:pb-2 p-2 pt-6">
                        <div className="flex items-center">
                            <div className="grow">
                                <div className="flex flex-col gap-2 justify-center items-center">
                                    <Logo cName="cursor-pointer fill-primary hover:fill-accent md:w-full w-[50%]" />
                                    <div className="text-base text-xs">Version {pckg.version}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <ul className="relative pt-6">
                        <li className="relative">
                            <Link to="" className={cName("item", menu, 0)} onClick={() => setMenu(0)}>
                                <MdOutlineNetworkCell className={cName("icon", menu, 0)} />
                                <span className={`md:block hidden ${cName("title", menu, 0)}`} >Networks</span>
                            </Link>
                        </li>
                        <li className="relative">
                            <Link to="" className={cName("item", menu, 1)} onClick={() => setMenu(1)}>
                                <MdOutlineOnlinePrediction className={cName("icon", menu, 1)} />
                                <span className={`md:block hidden ${cName("title", menu, 1)}`} >Bootnodes</span>
                            </Link>
                        </li>
                        <li className="relative">
                            <Link
                                rel="noreferrer"
                                to="https://ecosystem.ghostchain.io"
                                target="_blank"
                                className={cName("item", menu, 69)}
                            >
                                <RiGlobalLine className={cName("icon", menu, 69)} />
                                <span className={`md:block hidden ${cName("title", menu, 69)}`} >Ecosystem</span>
                            </Link>
                        </li>
                    </ul>
                    <div className="w-full text-center flex-grow flex flex-col justify-end">
                        <hr className="m-0" />
                        <div className="my-2 w-full h-[50px] flex flex-row justify-around items-center">
                            <Link
                                rel="noreferrer"
                                to="https://git.ghostchain.io/ghostchain/ghost-extension-wallet"
                                target="_blank"
                                className="text-base hover:text-accent"
                            >
                                <FaGithub className="w-6 h-6" />
                            </Link>
                            <Link
                                rel="noreferrer"
                                to="https://x.com/realGhostChain"
                                target="_blank"
                                className="text-base hover:text-accent"
                            >
                                <FaXTwitter className="w-6 h-6" />
                            </Link>
                            <Link
                                rel="noreferrer"
                                to="https://discord.com/invite/CvYP7vrqN3"
                                target="_blank"
                                className="text-base hover:text-accent"
                            >
                                <FaDiscord className="w-6 h-6" />
                            </Link>
                            <Link
                                rel="noreferrer"
                                to="https://t.me/realGhostChain"
                                target="_blank"
                                className="text-base hover:text-accent"
                            >
                                <FaTelegramPlane className="w-6 h-6" />
                            </Link>
                        </div>
                    </div>
                </div>
                <div className="w-[calc(100%-264px)] h-[100vh] overflow-auto grow flex-grow">
                    <MenuContent>
                        {menu === 0 ? (
                            <Networks />
                        ) : menu === 1 ? (
                            <Bootnodes />
                        ) : null}
                    </MenuContent>
                </div>
            </div>
        </>
    )
}
