import "@rainbow-me/rainbowkit/styles.css";

import {
  RainbowKitProvider,
  connectorsForWallets,
  darkTheme,
} from "@rainbow-me/rainbowkit";
import {
  imTokenWallet,
  tokenPocketWallet,
} from "@rainbow-me/rainbowkit/wallets";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import { http, createConfig, WagmiProvider, useReconnect } from "wagmi";
import { bsc } from "wagmi/chains";

const projectId =
  import.meta.env.VITE_WALLETCONNECT_PROJECT_ID || "ark-library-dev-only";

const connectors = connectorsForWallets(
  [
    {
      groupName: "ARK Library",
      wallets: [imTokenWallet, tokenPocketWallet],
    },
  ],
  {
    appName: "ARK Library",
    projectId,
  },
);

export const wagmiConfig = createConfig({
  chains: [bsc],
  connectors,
  ssr: false,
  transports: {
    [bsc.id]: http(),
  },
});

function WalletReconnectOnMount() {
  useReconnect();
  return null;
}

export function RainbowWalletProvider({ children }: { children: ReactNode }) {
  const [queryClient] = useState(() => new QueryClient());

  return (
    <WagmiProvider config={wagmiConfig}>
      <QueryClientProvider client={queryClient}>
        <WalletReconnectOnMount />
        <RainbowKitProvider
          modalSize="compact"
          theme={darkTheme({
            accentColor: "#d7b46a",
            accentColorForeground: "#08070c",
            borderRadius: "large",
            fontStack: "system",
            overlayBlur: "small",
          })}
        >
          {children}
        </RainbowKitProvider>
      </QueryClientProvider>
    </WagmiProvider>
  );
}

export function hasWalletConnectProjectId(): boolean {
  return Boolean(import.meta.env.VITE_WALLETCONNECT_PROJECT_ID);
}
