import { useUnstableProvider } from "../hooks"
import * as select from "@zag-js/select"
import { useMachine, normalizeProps } from "@zag-js/react"
import { useId, useEffect } from "react"
import { useChains } from "../hooks/useChains"

import { chainSpec as casperDevelopment } from "./chainspecs/casper_dev"

import {
    Select,
    SelectValue,
    SelectTrigger,
    SelectContent,
    SelectGroup,
    SelectItem,
} from "../components/ui/select"

const chainData = [
    {
        label: "Casper",
        value: "0x07074eb5f47a6f4dd70430674e5174d5414bc055292b90392fb6f0a28c7524d1",
        chainSpec: casperDevelopment,
    }
]

export const ChainSelect = () => {
    const {
        chainId,
        setChainId,
        provider,
        providerDetail,
        providerDetails,
        connectProviderDetail
    } = useUnstableProvider()

    const { chains: connectedChains } = useChains(provider)

    const isConnected = !!Object.keys(connectedChains).find(
        (connectedChainId) => connectedChainId === chainId,
    )

    useEffect(() => {
        // TODO: make sure we are using correct extension
        const maybeProvider = providerDetails?.find(obj => obj.info.rdns === "io.ghostchain.GhostWalletExtension")
        if (maybeProvider && !providerDetail) {
            try {
                connectProviderDetail(maybeProvider)
            } catch (e) {
                console.log(e)
            }
        }
    }, [providerDetail, providerDetails, connectProviderDetail])

    const chains = select.collection({
        items: chainData,
        itemToString: (item) => item.label,
        itemToValue: (item) => item.value,
    })

    const [state, send] = useMachine(
        select.machine({
            id: useId(),
            collection: chains,
            value: [chainId],
            onValueChange: (chainId) => setChainId(chainId.value[0] ?? ""),
        }),
    )

    const api = select.connect(state, send, normalizeProps)

    return (
        <div className="flex flex-col gap-2">
            <Select
                value={state.context.value[0]}
                onValueChange={(chainId) => {
                    let newValue = chainData.find(obj => obj.value === chainId)
                    api.selectValue(newValue?.value ? newValue.value : "")
                }}
            >
                <SelectTrigger
                    className={"text-muted-foreground w-[200px]"}
                    data-testid="chain-select"
                >
                    <SelectValue placeholder="Select Chain" />
                </SelectTrigger>
                <SelectContent>
                    <SelectGroup>
                        {[...chainData, { label: "Disconnect", value: "Disconnect"}].map(({ label, value }, index) => (
                            <SelectItem key={index} data-testid={`chain-${label}`} value={value}>{label}</SelectItem>
                        ))}
                    </SelectGroup>
                </SelectContent>
            </Select>
            {state.context.value[0] && (
                isConnected
                    ? <div className="text-center text-sm text-secondary font-bold tracking-wide bg-accent rounded">Connected</div>
                    : <div className="text-center text-sm text-secondary font-bold tracking-wide bg-destructive rounded">Connecting...</div>
            )}
        </div>
    )
}
