/**
 * GasOptimizer Component - Gas estimation and optimization
 */

import { useState, useEffect } from 'react'
import { fetchGasPrices, getRecommendedGasPrice, type GasPriceRecommendation } from '../../helpers/admin/gasOracle'
import { formatEther } from 'viem'

export default function GasOptimizer() {
  const [gasRecommendations, setGasRecommendations] = useState<GasPriceRecommendation | null>(null)
  const [estimatedGas, setEstimatedGas] = useState<string>('')
  const [estimatedCost, setEstimatedCost] = useState<string>('')
  const [urgency, setUrgency] = useState<'slow' | 'standard' | 'fast'>('standard')

  useEffect(() => {
    const loadGasPrices = async () => {
      const prices = await fetchGasPrices()
      setGasRecommendations(prices)
    }
    loadGasPrices()
    const interval = setInterval(loadGasPrices, 60000) // Update every minute
    return () => clearInterval(interval)
  }, [])

  const calculateCost = () => {
    if (!gasRecommendations || !estimatedGas) return

    const recommendation = getRecommendedGasPrice(gasRecommendations, urgency)
    const gasLimit = BigInt(estimatedGas || '21000')
    const maxFee = BigInt(recommendation.maxFeePerGas)
    const cost = gasLimit * maxFee
    setEstimatedCost(formatEther(cost))
  }

  useEffect(() => {
    calculateCost()
  }, [estimatedGas, urgency, gasRecommendations])

  if (!gasRecommendations) {
    return (
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <p className="text-white/60">Loading gas price recommendations...</p>
      </div>
    )
  }

  const recommendation = getRecommendedGasPrice(gasRecommendations, urgency)

  return (
    <div className="bg-black/20 rounded-xl p-6 border border-white/10">
      <h2 className="text-xl font-bold text-white mb-4">Gas Optimizer</h2>

      <div className="space-y-4">
        <div>
          <label className="block text-white/70 text-sm mb-2">Urgency Level</label>
          <div className="flex gap-2">
            {(['slow', 'standard', 'fast'] as const).map((level) => (
              <button
                key={level}
                onClick={() => setUrgency(level)}
                className={`flex-1 px-4 py-2 rounded-lg font-semibold transition-colors ${
                  urgency === level
                    ? 'bg-blue-600 text-white'
                    : 'bg-white/10 text-white/70 hover:bg-white/20'
                }`}
              >
                {level.charAt(0).toUpperCase() + level.slice(1)}
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div className="bg-white/5 rounded-lg p-4">
            <div className="text-white/70 text-sm mb-1">Max Fee Per Gas</div>
            <div className="text-white font-mono text-lg">
              {(BigInt(recommendation.maxFeePerGas) / BigInt(1e9)).toString()} Gwei
            </div>
          </div>
          <div className="bg-white/5 rounded-lg p-4">
            <div className="text-white/70 text-sm mb-1">Priority Fee</div>
            <div className="text-white font-mono text-lg">
              {(BigInt(recommendation.maxPriorityFeePerGas) / BigInt(1e9)).toString()} Gwei
            </div>
          </div>
        </div>

        <div>
          <label className="block text-white/70 text-sm mb-2">Estimated Gas Limit</label>
          <input
            type="number"
            value={estimatedGas}
            onChange={(e) => setEstimatedGas(e.target.value)}
            placeholder="21000"
            className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
          />
        </div>

        {estimatedCost && (
          <div className="bg-blue-500/20 border border-blue-500/50 rounded-lg p-4">
            <div className="text-blue-200 text-sm mb-1">Estimated Cost</div>
            <div className="text-blue-100 font-bold text-xl">{estimatedCost} ETH</div>
          </div>
        )}

        <div className="text-white/60 text-xs">
          <p>Base Fee: {(BigInt(gasRecommendations.estimatedBaseFee) / BigInt(1e9)).toString()} Gwei</p>
          <p>Block: {gasRecommendations.blockNumber}</p>
        </div>
      </div>
    </div>
  )
}
