'use client'

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { useAccount, useDisconnect, useConnect } from 'wagmi'
import { useWeb3Modal } from '@web3modal/wagmi/react'

interface MockWalletContextType {
  isConnected: boolean
  address: string
  isDemo: boolean
  openConnectModal: () => void
  closeConnectModal: () => void
  disconnectWallet: () => void
}

const MockWalletContext = createContext<MockWalletContextType | undefined>(undefined)

// Custom Modal Component that mimics Web3Modal
function MockConnectModal({
  onClose,
  onConnect,
  onMetaMaskClick,
}: {
  onClose: () => void
  onConnect: (address: string) => void
  onMetaMaskClick?: () => void
}) {
  const [customAddr, setCustomAddr] = useState('0x9db2B7CDeE7363402434E0a3B3D2d7301c238b1E')

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/75 backdrop-blur-sm p-4 animate-fadeIn">
      <div className="w-full max-w-[360px] bg-[#191a1a] border border-zinc-800/80 rounded-[30px] p-5 text-slate-100 flex flex-col shadow-2xl relative select-none">
        
        {/* Header */}
        <div className="flex items-center justify-between text-zinc-400 mb-2">
          <button className="text-zinc-500 hover:text-zinc-300 transition-colors p-1">
            <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" />
            </svg>
          </button>
          <span className="font-semibold text-[14px] text-zinc-200 tracking-wide">Connect Wallet</span>
          <button onClick={onClose} className="text-zinc-500 hover:text-zinc-300 transition-colors p-1">
            <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Email Input */}
        <div className="mt-2 relative">
          <span className="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-zinc-500">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75" />
            </svg>
          </span>
          <input
            type="email"
            placeholder="Email"
            className="w-full pl-10 pr-4 py-2 bg-zinc-900/60 border border-zinc-800/80 rounded-2xl text-xs placeholder-zinc-500 focus:outline-none focus:border-zinc-700 text-white"
            readOnly
            value="demo@mte7star.com"
          />
        </div>

        {/* Google Login */}
        <button
          onClick={() => onConnect(customAddr)}
          className="mt-2 w-full flex items-center justify-center gap-2 py-2 bg-zinc-900/60 hover:bg-zinc-850 border border-zinc-800/80 rounded-2xl text-xs font-semibold transition-colors cursor-pointer text-white"
        >
          <svg className="w-4 h-4" viewBox="0 0 24 24">
            <path fill="#EA4335" d="M12.24 10.285V14.4h6.887c-.275 1.565-1.88 4.604-6.887 4.604-4.33 0-7.859-3.579-7.859-8s3.53-8 7.859-8c2.46 0 4.105 1.025 5.047 1.926l3.227-3.11C18.281 1.09 15.578 0 12.24 0 5.58 0 0 5.37 0 12s5.58 12 12.24 12c6.96 0 11.57-4.89 11.57-11.79 0-.795-.085-1.4-.19-1.925H12.24z" />
          </svg>
          Continue With Google
        </button>

        {/* Social Row */}
        <div className="mt-2 flex gap-1.5 justify-between">
          {['x', 'discord', 'farcaster', 'github'].map((social) => (
            <button
              key={social}
              onClick={() => onConnect(customAddr)}
              className="flex-1 flex justify-center items-center py-2 bg-zinc-900/60 border border-zinc-800/80 rounded-xl text-zinc-400 hover:text-white transition-all cursor-pointer"
            >
              {social === 'x' && (
                <svg className="w-3.5 h-3.5 fill-current" viewBox="0 0 24 24">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                </svg>
              )}
              {social === 'discord' && (
                <svg className="w-3.5 h-3.5 fill-current" viewBox="0 0 127.14 96.36">
                  <path d="M107.7,8.07A105.15,105.15,0,0,0,77.26,0a77.19,77.19,0,0,0-3.3,6.83A96.67,96.67,0,0,0,53.22,6.83,77.19,77.19,0,0,0,49.88,0,105.15,105.15,0,0,0,19.44,8.07C3.66,31.58-1.86,54.65,1,77.53A105.73,105.73,0,0,0,32,96.36a77.7,77.7,0,0,0,6.63-10.85,68.43,68.43,0,0,1-10.5-5c.88-.65,1.72-1.34,2.51-2a75.58,75.58,0,0,0,73,0c.8.71,1.63,1.4,2.52,2a68.43,68.43,0,0,1-10.5,5,77.7,77.7,0,0,0,6.63,10.85,105.73,105.73,0,0,0,32.58-18.83C129,54.65,122.94,31.58,107.7,8.07ZM42.45,65.69C36.18,65.69,31,60,31,53S36.18,40.36,42.45,40.36,53.83,46,53.83,53,48.72,65.69,42.45,65.69Zm42.24,0C78.41,65.69,73.24,60,73.24,53S78.41,40.36,84.69,40.36,96.07,46,96.07,53,91,65.69,84.69,65.69Z" />
                </svg>
              )}
              {social === 'farcaster' && (
                <span className="text-[10px] font-bold text-purple-400">FC</span>
              )}
              {social === 'github' && (
                <svg className="w-3.5 h-3.5 fill-current" viewBox="0 0 24 24">
                  <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
                </svg>
              )}
            </button>
          ))}
          <button
            onClick={() => onConnect(customAddr)}
            className="flex-1 flex justify-center items-center py-2 bg-zinc-900/60 border border-zinc-800/80 rounded-xl text-zinc-400 hover:text-white transition-all cursor-pointer"
          >
            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="3" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
            </svg>
          </button>
        </div>

        {/* Divider */}
        <div className="my-3 flex items-center justify-center">
          <div className="w-full border-t border-zinc-800/40"></div>
          <span className="px-3 text-[10px] text-zinc-500 font-semibold bg-[#191a1a]">or</span>
          <div className="w-full border-t border-zinc-800/40"></div>
        </div>

        {/* Wallets */}
        <div className="flex flex-col gap-1.5 max-h-[220px] overflow-y-auto">
          {/* WalletConnect */}
          <button
            onClick={() => onConnect(customAddr)}
            className="w-full flex items-center justify-between p-2.5 bg-zinc-900/40 hover:bg-zinc-900 border border-zinc-800/40 rounded-xl transition-all cursor-pointer text-left text-zinc-200 text-xs"
          >
            <div className="flex items-center gap-2.5">
              <div className="w-6 h-6 rounded-lg bg-blue-500/20 flex items-center justify-center text-blue-400">
                <svg className="w-4.5 h-4.5" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M4.17 6.4C8.49 2.1 15.51 2.1 19.83 6.4L20.88 7.45C21.1 7.67 21.1 8.03 20.88 8.25L18.8 10.33C18.58 10.55 18.22 10.55 18 10.33L17.23 9.56C14.35 6.68 9.65 6.68 6.77 9.56L5.8 10.53C5.58 10.75 5.22 10.75 5 10.53L2.92 8.45C2.7 8.23 2.7 7.87 2.92 7.65L4.17 6.4ZM18 12.33C14.68 9 9.32 9 6 12.33L4.95 13.38C4.73 13.6 4.73 13.96 4.95 14.18L7.03 16.26C7.25 16.48 7.61 16.48 7.83 16.26L8.6 15.49C10.48 13.61 13.52 13.61 15.4 15.49L16.23 16.32C16.45 16.54 16.81 16.54 17.03 16.32L19.11 14.24C19.33 14.02 19.33 13.66 19.11 13.44L18 12.33Z" />
                </svg>
              </div>
              <span className="font-semibold">WalletConnect</span>
            </div>
            <span className="bg-blue-500/10 text-blue-400 border border-blue-500/20 text-[9px] font-bold px-1.5 py-0.5 rounded">QR CODE</span>
          </button>

          {/* MetaMask */}
          <button
            onClick={() => {
              if (onMetaMaskClick) {
                onMetaMaskClick()
              } else {
                onConnect(customAddr)
              }
            }}
            className="w-full flex items-center justify-between p-2.5 bg-zinc-900/40 hover:bg-zinc-900 border border-zinc-800/40 rounded-xl transition-all cursor-pointer text-left text-zinc-200 text-xs"
          >
            <div className="flex items-center gap-2.5">
              <span className="text-base select-none">🦊</span>
              <span className="font-semibold">MetaMask</span>
            </div>
            <span className="bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[9px] font-bold px-1.5 py-0.5 rounded">INSTALLED</span>
          </button>

          {/* Brave Wallet */}
          <button
            onClick={() => onConnect(customAddr)}
            className="w-full flex items-center justify-between p-2.5 bg-zinc-900/40 hover:bg-zinc-900 border border-zinc-800/40 rounded-xl transition-all cursor-pointer text-left text-zinc-200 text-xs"
          >
            <div className="flex items-center gap-2.5">
              <span className="text-base select-none">🦁</span>
              <span className="font-semibold">Brave Wallet</span>
            </div>
            <span className="bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[9px] font-bold px-1.5 py-0.5 rounded">INSTALLED</span>
          </button>

          {/* All Wallets */}
          <button
            onClick={() => onConnect(customAddr)}
            className="w-full flex items-center justify-between p-2.5 bg-zinc-900/40 hover:bg-zinc-900 border border-zinc-800/40 rounded-xl transition-all cursor-pointer text-left text-zinc-200 text-xs"
          >
            <div className="flex items-center gap-2.5">
              <div className="w-6 h-6 rounded-lg bg-zinc-800 flex items-center justify-center text-zinc-400">
                <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M4 4h4v4H4V4zm6 0h4v4h-4V4zm6 0h4v4h-4V4zM4 10h4v4H4v-4zm6 0h4v4h-4v-4zm6 0h4v4h-4v-4zM4 16h4v4H4v-4zm6 0h4v4h-4v-4zm6 0h4v4h-4v-4z" />
                </svg>
              </div>
              <span className="font-semibold">All Wallets</span>
            </div>
            <span className="bg-zinc-800 text-zinc-400 border border-zinc-700/50 text-[9px] font-bold px-1.5 py-0.5 rounded">350+</span>
          </button>
        </div>

        {/* Demo Wallet Configuration */}
        <div className="mt-3.5 pt-3 border-t border-zinc-850/60 flex flex-col gap-1.5">
          <label className="text-[9px] uppercase font-bold tracking-wider text-zinc-500 px-0.5">Demo Wallet Address (Customizable)</label>
          <input
            type="text"
            value={customAddr}
            onChange={(e) => setCustomAddr(e.target.value)}
            className="w-full px-3 py-1.5 bg-zinc-950 border border-zinc-850 rounded-xl text-xs font-mono focus:outline-none focus:border-zinc-750 text-zinc-300"
            placeholder="0x..."
          />
        </div>

      </div>
    </div>
  )
}

export function MockWalletProvider({ children }: { children: ReactNode }) {
  const [mounted, setMounted] = useState(false)
  const { address, isConnected } = useAccount()
  const { disconnect } = useDisconnect()
  const { open, close } = useWeb3Modal()
  const { connect, connectors } = useConnect()

  // Demo connection state
  const [isDemoConnected, setIsDemoConnected] = useState(false)
  const [demoAddress, setDemoAddress] = useState('')
  const [isModalOpen, setIsModalOpen] = useState(false)

  useEffect(() => {
    setMounted(true)
    const savedConnected = localStorage.getItem('demoWalletConnected') === 'true'
    const savedAddress = localStorage.getItem('demoWalletAddress') || ''
    if (savedConnected && savedAddress) {
      setIsDemoConnected(true)
      setDemoAddress(savedAddress)
    }
  }, [])

  const openConnectModal = async () => {
    if (typeof window !== 'undefined' && window.ethereum) {
      try {
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: '0x61' }] // BSC Testnet
        })
      } catch (err: any) {
        if (err.code === 4902) {
          try {
            await window.ethereum.request({
              method: 'wallet_addEthereumChain',
              params: [
                {
                  chainId: '0x61',
                  chainName: 'BSC Testnet',
                  nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },
                  rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
                  blockExplorerUrls: ['https://testnet.bscscan.com']
                }
              ]
            })
          } catch (addErr) {
            console.error('Failed to add network:', addErr)
          }
        }
      }
      
      const metamaskConnector = connectors.find((c) => c.id === 'metaMask' || c.name.toLowerCase().includes('metamask'))
      if (metamaskConnector) {
        connect({ connector: metamaskConnector })
      } else {
        await window.ethereum.request({ method: 'eth_requestAccounts' })
      }
    } else {
      setIsModalOpen(true)
    }
  }

  const closeConnectModal = () => {
    setIsModalOpen(false)
  }

  const handleDemoConnect = (address: string) => {
    const cleanAddress = address.trim() || '0x9db2B7CDeE7363402434E0a3B3D2d7301c238b1E'
    setIsDemoConnected(true)
    setDemoAddress(cleanAddress)
    localStorage.setItem('demoWalletConnected', 'true')
    localStorage.setItem('demoWalletAddress', cleanAddress)
    localStorage.setItem('testMode', 'true')
    setIsModalOpen(false)

    // Trigger auth state updates across the app
    window.dispatchEvent(new Event('mockWalletConnected'))
  }

  const disconnectWallet = () => {
    disconnect()
    setIsDemoConnected(false)
    setDemoAddress('')
    localStorage.removeItem('demoWalletConnected')
    localStorage.removeItem('demoWalletAddress')
    localStorage.removeItem('memberSession')
    localStorage.removeItem('testMode')

    // Trigger auth state update across the application
    window.dispatchEvent(new Event('mockWalletDisconnected'))
    window.dispatchEvent(new Event('mockWalletConnected'))
  }

  // Handle cross-tab or page login state events
  useEffect(() => {
    if (!mounted) return
    const isWalletConnected = isDemoConnected || isConnected
    const walletAddress = isDemoConnected ? demoAddress : address

    if (isWalletConnected && walletAddress) {
      window.dispatchEvent(new Event('mockWalletConnected'))
    } else {
      window.dispatchEvent(new Event('mockWalletDisconnected'))
    }
  }, [isConnected, address, isDemoConnected, demoAddress, mounted])

  // Clear demo connection if real connection is established
  useEffect(() => {
    if (mounted && isConnected) {
      setIsDemoConnected(false)
      localStorage.removeItem('demoWalletConnected')
      localStorage.removeItem('demoWalletAddress')
      localStorage.removeItem('testMode')
    }
  }, [isConnected, mounted])

  const handleMetaMaskClick = async () => {
    closeConnectModal()
    if (typeof window !== 'undefined' && window.ethereum) {
      try {
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: '0x61' }] // BSC Testnet
        })
      } catch (err: any) {
        if (err.code === 4902) {
          try {
            await window.ethereum.request({
              method: 'wallet_addEthereumChain',
              params: [
                {
                  chainId: '0x61',
                  chainName: 'BSC Testnet',
                  nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },
                  rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
                  blockExplorerUrls: ['https://testnet.bscscan.com']
                }
              ]
            })
          } catch (addErr) {
            console.error('Failed to add network:', addErr)
          }
        }
      }
      open()
    } else {
      alert('MetaMask is not installed. Please install it or use Demo Mode.')
    }
  }

  const finalConnected = isDemoConnected || (mounted && isConnected)
  const finalAddress = isDemoConnected ? demoAddress : (mounted && address ? address : '')

  const value = {
    isConnected: finalConnected,
    address: finalAddress,
    isDemo: isDemoConnected,
    openConnectModal,
    closeConnectModal,
    disconnectWallet,
  }

  return (
    <MockWalletContext.Provider value={value}>
      {children}
      {isModalOpen && (
        <MockConnectModal 
          onClose={closeConnectModal} 
          onConnect={handleDemoConnect} 
          onMetaMaskClick={handleMetaMaskClick}
        />
      )}
    </MockWalletContext.Provider>
  )
}

export function useMetaMaskValidation() {
  const [isInstalled, setIsInstalled] = useState(false)
  const [isCorrectNetwork, setIsCorrectNetwork] = useState(false)
  const { chain } = useAccount()

  useEffect(() => {
    setIsInstalled(typeof window !== 'undefined' && !!window.ethereum)
  }, [])

  useEffect(() => {
    if (chain) {
      setIsCorrectNetwork(chain.id === 97)
    }
  }, [chain])

  return { isInstalled, isCorrectNetwork }
}

export function useMockWallet() {
  const context = useContext(MockWalletContext)
  if (!context) {
    throw new Error('useMockWallet must be used within a MockWalletProvider')
  }
  return context
}
