import { useEffect, useState } from 'react'
import { estimatePlatformFunds } from '@/lib/fundingCalculation'
import { t } from '@/lib/i18n'

interface FundingProgressBarProps {
  progressPercent: number
}

function FundingProgressBar({ progressPercent }: FundingProgressBarProps) {
  return (
    <div className="relative w-full h-4 bg-cyber-dark rounded-full overflow-hidden border border-neon-cyan/30">
      <div
        className="absolute top-0 left-0 h-full bg-gradient-to-r from-neon-cyan to-neon-green transition-all duration-500"
        style={{ width: `${progressPercent}%` }}
      />
      <div className="absolute inset-0 flex items-center justify-center">
        <span className="text-xs font-mono text-cyber-darker font-bold">
          {progressPercent.toFixed(1)}%
        </span>
      </div>
    </div>
  )
}

function FundingStats({ stats }: { stats: ReturnType<typeof estimatePlatformFunds> }) {
  const progressPercent = Math.min(100, stats.progressPercent)
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between text-sm">
        <span className="text-cyber-accent">{t('home.funding.current', { current: stats.totalBTC.toFixed(6) })}</span>
        <span className="text-cyber-accent">{t('home.funding.target', { target: stats.targetBTC.toFixed(2) })}</span>
      </div>
      <FundingProgressBar progressPercent={progressPercent} />
      <p className="text-xs text-cyber-accent/70">
        {t('home.funding.progress', { percent: progressPercent.toFixed(1) })}
      </p>
      <p className="text-sm text-cyber-accent mt-4">
        {t('home.funding.description')}
      </p>
    </div>
  )
}

export function FundingGauge() {
  const [stats, setStats] = useState(estimatePlatformFunds())
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // In a real implementation, this would fetch actual data
    // For now, we use the estimate
    const loadStats = async () => {
      try {
        const fundingStats = estimatePlatformFunds()
        setStats(fundingStats)
      } catch (e) {
        console.error('Error loading funding stats:', e)
      } finally {
        setLoading(false)
      }
    }
    void loadStats()
  }, [])

  if (loading) {
    return (
      <div className="bg-cyber-dark/50 border border-neon-cyan/20 rounded-lg p-6 mb-8">
        <p className="text-cyber-accent">{t('common.loading')}</p>
      </div>
    )
  }

  return (
    <div className="bg-cyber-dark/50 border border-neon-cyan/20 rounded-lg p-6 mb-8">
      <h2 className="text-xl font-semibold text-neon-cyan mb-4">{t('home.funding.title')}</h2>
      <FundingStats stats={stats} />
    </div>
  )
}
