import useSWR from "swr"

import { getDynamicBuilder, getLookupFn } from "@polkadot-api/metadata-builders"
import { mergeUint8, toHex } from "@polkadot-api/utils"
import { type SS58String, Enum } from "@polkadot-api/substrate-bindings"

import { useUnstableProvider } from "./useUnstableProvider"
import { useMetadata } from "./useMetadata"

const AccountId = (value: SS58String) => Enum<
    {
        type: "Id"
        value: SS58String
    },
    "Id"
>("Id", value)

export const useTransferCalldata = (destination: SS58String | undefined, amount: bigint | undefined) => {
    const { client, chainId } = useUnstableProvider()
    const metadata = useMetadata()
    const { data: calldata } = useSWR(
        client && chainId && destination && amount && metadata
            ? ["metadata", client, chainId, metadata, destination, amount]
            : null,
        ([_, client, _chainId, metadata, destination, amount]) => {
            const builder = getDynamicBuilder(getLookupFn(metadata))
            const { codec, location } = builder.buildCall("Balances", "transfer_allow_death")

            return toHex(
                mergeUint8(
                    new Uint8Array(location),
                    codec.enc({
                        dest: AccountId(destination),
                        value: amount,
                    }),
                ),
            )
        }
    )
    return calldata
}
