'use client'

import { useState } from 'react'

const CHAIN_138 = {
  chainId: '0x8a',
  chainName: 'DeFi Oracle Meta Mainnet',
  nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
  rpcUrls: ['https://rpc-http-pub.d-bis.org', 'https://rpc.d-bis.org', 'https://rpc2.d-bis.org'],
  blockExplorerUrls: ['https://explorer.d-bis.org'],
}

const CHAIN_MAINNET = {
  chainId: '0x1',
  chainName: 'Ethereum Mainnet',
  nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
  rpcUrls: ['https://eth.llamarpc.com', 'https://rpc.ankr.com/eth', 'https://ethereum.publicnode.com'],
  blockExplorerUrls: ['https://etherscan.io'],
}

const CHAIN_ALL_MAINNET = {
  chainId: '0x9f2c4',
  chainName: 'ALL Mainnet',
  nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
  rpcUrls: ['https://mainnet-rpc.alltra.global'],
  blockExplorerUrls: ['https://alltra.global'],
}

export function AddToMetaMask() {
  const [status, setStatus] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const ethereum = typeof window !== 'undefined' ? (window as unknown as { ethereum?: { request: (args: { method: string; params: unknown[] }) => Promise<unknown> } }).ethereum : undefined

  const addChain = async (chain: typeof CHAIN_138) => {
    setError(null)
    setStatus(null)
    if (!ethereum) {
      setError('MetaMask or another Web3 wallet is not installed.')
      return
    }
    try {
      await ethereum.request({
        method: 'wallet_addEthereumChain',
        params: [chain],
      })
      setStatus(`Added ${chain.chainName}. You can switch to it in your wallet.`)
    } catch (e) {
      const err = e as { code?: number; message?: string }
      if (err.code === 4902) {
        setStatus(`Added ${chain.chainName}. You can switch to it in your wallet.`)
      } else {
        setError(err.message || 'Failed to add network')
      }
    }
  }

  // Production (explorer.d-bis.org): same origin; dev: NEXT_PUBLIC_API_URL or localhost
  const apiBase =
    typeof window !== 'undefined'
      ? process.env.NEXT_PUBLIC_API_URL || window.location.origin
      : process.env.NEXT_PUBLIC_API_URL || 'https://explorer.d-bis.org'
  const tokenListUrl = apiBase.replace(/\/$/, '') + '/api/config/token-list'

  return (
    <div className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4 space-y-4">
      <h2 className="text-lg font-semibold">Add to MetaMask</h2>
      <p className="text-sm text-gray-600 dark:text-gray-400">
        Add Chain 138 (DeFi Oracle Meta Mainnet), Ethereum Mainnet, or ALL Mainnet to your wallet. Then add the token list URL in MetaMask Settings so tokens appear automatically.
      </p>
      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          onClick={() => addChain(CHAIN_138)}
          className="px-4 py-2 rounded bg-primary-600 text-white hover:bg-primary-700 text-sm font-medium"
        >
          Add Chain 138
        </button>
        <button
          type="button"
          onClick={() => addChain(CHAIN_MAINNET)}
          className="px-4 py-2 rounded bg-gray-600 text-white hover:bg-gray-700 text-sm font-medium"
        >
          Add Ethereum Mainnet
        </button>
        <button
          type="button"
          onClick={() => addChain(CHAIN_ALL_MAINNET)}
          className="px-4 py-2 rounded bg-gray-600 text-white hover:bg-gray-700 text-sm font-medium"
        >
          Add ALL Mainnet
        </button>
      </div>
      <div className="text-sm">
        <p className="text-gray-600 dark:text-gray-400 mb-1">Token list URL (add in MetaMask Settings → Token lists):</p>
        <code className="block p-2 rounded bg-gray-100 dark:bg-gray-900 break-all text-xs">{tokenListUrl}</code>
      </div>
      {status && <p className="text-sm text-green-600 dark:text-green-400">{status}</p>}
      {error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
    </div>
  )
}
