"use client";

import { type ReactNode, useEffect, useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createAppKit } from "@reown/appkit/react";
import { WagmiProvider, type Config } from "wagmi";
import type { WagmiAdapter } from "@reown/appkit-adapter-wagmi";
import {
  getRuntimeConfig,
  networks,
  createWagmiAdapter,
} from "@/lib/config";

const queryClient = new QueryClient();

export default function Providers({ children }: { children: ReactNode }) {
  const [adapter, setAdapter] = useState<WagmiAdapter | null>(null);

  useEffect(() => {
    let mounted = true;
    getRuntimeConfig().then(({ projectId }) => {
      if (!mounted) return;

      const wagmiAdapter = createWagmiAdapter(projectId);

      createAppKit({
        adapters: [wagmiAdapter],
        projectId,
        networks,
        metadata: {
          name: "prpc Signing UI",
          description: "Proxy RPC signing interface",
          url: window.location.origin,
          icons: [],
        },
        features: { analytics: false },
      });

      setAdapter(wagmiAdapter);
    });
    return () => {
      mounted = false;
    };
  }, []);

  if (!adapter) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-zinc-50 dark:bg-zinc-950">
        <p className="text-sm text-zinc-500">Loading config...</p>
      </div>
    );
  }

  return (
    <WagmiProvider config={adapter.wagmiConfig as Config}>
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    </WagmiProvider>
  );
}
