'use client'
import React, { useState } from 'react'

export default function WalletConnection({ onWalletConnected }) {
  const [walletAddress, setWalletAddress] = useState('')
  const [isConnecting, setIsConnecting] = useState(false)
  const [connectionStatus, setConnectionStatus] = useState(null)

  const connectPhantomWallet = async () => {
    setIsConnecting(true)
    try {
      // Check if Phantom wallet is available
      if (typeof window !== 'undefined' && window.solana && window.solana.isPhantom) {
        const response = await window.solana.connect()
        const address = response.publicKey.toString()
        setWalletAddress(address)
        setConnectionStatus({ success: true, message: 'Wallet connected successfully!' })
        
        if (onWalletConnected) {
          onWalletConnected(address)
        }
      } else {
        setConnectionStatus({ 
          success: false, 
          message: 'Phantom wallet not found. Please install Phantom wallet extension.' 
        })
      }
    } catch (error) {
      setConnectionStatus({ 
        success: false, 
        message: `Failed to connect wallet: ${error.message}` 
      })
    } finally {
      setIsConnecting(false)
    }
  }

  const connectManualAddress = () => {
    if (walletAddress.length >= 32) {
      setConnectionStatus({ success: true, message: 'Manual address set!' })
      if (onWalletConnected) {
        onWalletConnected(walletAddress)
      }
    } else {
      setConnectionStatus({ 
        success: false, 
        message: 'Please enter a valid Solana wallet address' 
      })
    }
  }

  const disconnectWallet = () => {
    setWalletAddress('')
    setConnectionStatus(null)
    if (onWalletConnected) {
      onWalletConnected(null)
    }
  }

  return (
    <div className="card card-gradient p-6">
      <h2 className="text-xl font-bold text-white mb-4">Wallet Connection</h2>
      
      {!walletAddress ? (
        <div className="space-y-4">
          {/* Phantom Wallet Connection */}
          <div>
            <button
              onClick={connectPhantomWallet}
              disabled={isConnecting}
              className="w-full py-3 px-4 bg-purple-600 hover:bg-purple-700 disabled:opacity-50 text-white font-bold rounded-lg transition-colors flex items-center justify-center space-x-2"
            >
              {isConnecting ? (
                <>
                  <div className="spinner"></div>
                  <span>Connecting...</span>
                </>
              ) : (
                <>
                  <span>👻</span>
                  <span>Connect Phantom Wallet</span>
                </>
              )}
            </button>
          </div>

          {/* Manual Address Input */}
          <div className="border-t border-gray-700 pt-4">
            <label className="block text-sm font-medium text-gray-300 mb-2">
              Or enter wallet address manually:
            </label>
            <div className="flex space-x-2">
              <input
                type="text"
                value={walletAddress}
                onChange={(e) => setWalletAddress(e.target.value)}
                placeholder="Enter Solana wallet address..."
                className="flex-1 px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <button
                onClick={connectManualAddress}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
              >
                Set
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="p-4 bg-green-900 border border-green-600 rounded-lg">
            <div className="flex items-center justify-between">
              <div>
                <div className="text-green-400 font-bold">✅ Wallet Connected</div>
                <div className="text-sm text-gray-300 font-mono break-all">
                  {walletAddress.substring(0, 8)}...{walletAddress.substring(walletAddress.length - 8)}
                </div>
              </div>
              <button
                onClick={disconnectWallet}
                className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-sm rounded"
              >
                Disconnect
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Connection Status */}
      {connectionStatus && (
        <div className={`mt-4 p-3 rounded-lg ${
          connectionStatus.success 
            ? 'bg-green-900 border border-green-600 text-green-400' 
            : 'bg-red-900 border border-red-600 text-red-400'
        }`}>
          {connectionStatus.message}
        </div>
      )}

      {/* Instructions */}
      <div className="mt-4 text-xs text-gray-500">
        <p>💡 Connect your Solana wallet to see real portfolio balance and execute trades.</p>
        <p>🔒 Your wallet address is only used to fetch balance - no private keys are stored.</p>
      </div>
    </div>
  )
}
