'use client';

import { getDefaultConfig, RainbowKitProvider, darkTheme, lightTheme } from '@rainbow-me/rainbowkit';
import { WagmiProvider } from 'wagmi';
import { mainnet, polygon, optimism, arbitrum, base, sepolia } from 'wagmi/chains';
import { QueryClientProvider, QueryClient } from '@tanstack/react-query';
import { ThemeProvider, useTheme } from 'next-themes';
import { useEffect, useState } from 'react';
import { defineChain } from 'viem';

import { TranslationsProvider } from '@/providers/translations-provider';
import { Header } from '@/components/header';
import { ToastProvider } from '@/components/ui/toast';

import deployments from '@/contracts/liqp-deployments.json';

const mockchain = defineChain({
  id: 31337,
  name: 'Mockchain',
  nativeCurrency: {
    decimals: 18,
    name: 'Test Ether',
    symbol: 'TETH',
  },
  rpcUrls: {
    default: { http: ['http://localhost:8545'] },
  },
  testnet: true,
});

const allChains = [mainnet, polygon, optimism, arbitrum, base, sepolia, mockchain];
const chains = allChains.filter(chain =>
    Object.keys(deployments || {}).includes(chain.id.toString())
);
if (chains.length === 0) {
    console.error('No chains found with deployed contracts.');
}

const config = getDefaultConfig({
    appName: 'Liquidity Party',
    projectId: 'YOUR_PROJECT_ID', // Get this from https://cloud.walletconnect.com
    chains: chains as any,
    ssr: false,
});

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      refetchOnReconnect: false,
      retry: false,
      staleTime: 5 * 60 * 1000, // 5 minutes
    },
  },
});

function Web3Provider({ children }: { children: React.ReactNode }) {
  const { theme } = useTheme();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  // Use dark theme by default until mounted, then follow the actual theme
  const rainbowKitTheme = !mounted || theme === 'dark' 
    ? darkTheme({
        accentColor: '#a855f7', // Purple to match your primary color
        accentColorForeground: 'white',
      })
    : lightTheme({
        accentColor: '#a855f7',
        accentColorForeground: 'white',
      });

  return (
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        <RainbowKitProvider theme={rainbowKitTheme}>
          {children}
        </RainbowKitProvider>
      </QueryClientProvider>
    </WagmiProvider>
  );
}

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <TranslationsProvider>
      <ThemeProvider
        attribute="class"
        defaultTheme="dark"
        enableSystem={false}
        storageKey="liquidity-party-theme"
      >
        <Web3Provider>
          <ToastProvider>
            <div className="min-h-screen flex flex-col">
              <Header />
              <main className="flex-1 container mx-auto px-4 py-8">
                {children}
              </main>
            </div>
          </ToastProvider>
        </Web3Provider>
      </ThemeProvider>
    </TranslationsProvider>
  );
}
