'use client'

import { useEffect, useState } from 'react'
import { api } from '@/lib/api'
import {
  DollarSign,
  TrendingUp,
  Users,
  Crown,
  Zap,
  RefreshCw,
  Loader2,
  ArrowUpRight,
  ArrowDownRight,
  Coins,
} from 'lucide-react'
import clsx from 'clsx'

interface EarningsData {
  mrr: number
  arr: number
  paying_customers: number
  tier_breakdown: {
    scout: { count: number; revenue: number }
    trader: { count: number; revenue: number }
    tycoon: { count: number; revenue: number }
  }
  new_subscriptions: { week: number; month: number }
  churn: { month: number }
  yield_revenue_month: number
  total_revenue_month: number
  timestamp: string
}

export function EarningsTab() {
  const [data, setData] = useState<EarningsData | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const loadData = async () => {
    try {
      const earnings = await api.getAdminEarnings()
      setData(earnings)
    } catch (err) {
      console.error('Failed to load earnings:', err)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  const handleRefresh = () => {
    setRefreshing(true)
    loadData()
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-6 h-6 text-red-400 animate-spin" />
      </div>
    )
  }

  if (!data) {
    return (
      <div className="text-center py-20">
        <DollarSign className="w-12 h-12 text-white/10 mx-auto mb-4" />
        <p className="text-white/40 font-mono">Failed to load earnings data</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header Actions */}
      <div className="flex items-center justify-between">
        <div>
          <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Revenue Dashboard</p>
          <p className="text-xs text-white/30 font-mono mt-1">
            Last updated: {new Date(data.timestamp).toLocaleString()}
          </p>
        </div>
        <button
          onClick={handleRefresh}
          disabled={refreshing}
          className="flex items-center gap-2 px-4 py-2 border border-white/10 text-white/60 hover:text-white hover:bg-white/5 transition-all disabled:opacity-50"
        >
          <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
          Refresh
        </button>
      </div>

      {/* Main Revenue Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* MRR */}
        <div className="relative overflow-hidden border border-red-500/30 bg-gradient-to-br from-red-500/10 to-red-500/5 p-6">
          <div className="absolute top-0 right-0 w-32 h-32 bg-red-500/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
          <div className="relative">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-10 h-10 bg-red-500/20 flex items-center justify-center">
                <DollarSign className="w-5 h-5 text-red-400" />
              </div>
              <span className="text-[10px] font-mono text-red-400/60 uppercase tracking-wider">Monthly Recurring</span>
            </div>
            <div className="text-4xl font-bold text-white font-mono tracking-tight">
              ${data.mrr.toLocaleString()}
            </div>
            <div className="text-xs text-white/40 font-mono mt-2">MRR</div>
          </div>
        </div>

        {/* ARR */}
        <div className="relative overflow-hidden border border-accent/30 bg-gradient-to-br from-accent/10 to-accent/5 p-6">
          <div className="absolute top-0 right-0 w-32 h-32 bg-accent/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
          <div className="relative">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-10 h-10 bg-accent/20 flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-accent" />
              </div>
              <span className="text-[10px] font-mono text-accent/60 uppercase tracking-wider">Annual Recurring</span>
            </div>
            <div className="text-4xl font-bold text-white font-mono tracking-tight">
              ${data.arr.toLocaleString()}
            </div>
            <div className="text-xs text-white/40 font-mono mt-2">ARR</div>
          </div>
        </div>

        {/* Paying Customers */}
        <div className="border border-white/10 bg-white/[0.02] p-6">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-10 h-10 bg-white/5 flex items-center justify-center">
              <Users className="w-5 h-5 text-white/60" />
            </div>
            <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Paying Customers</span>
          </div>
          <div className="text-4xl font-bold text-white font-mono tracking-tight">
            {data.paying_customers}
          </div>
          <div className="flex items-center gap-2 mt-2">
            <span className="text-xs text-accent font-mono flex items-center gap-1">
              <ArrowUpRight className="w-3 h-3" />
              +{data.new_subscriptions.week} this week
            </span>
          </div>
        </div>

        {/* Yield Revenue */}
        <div className="border border-amber-500/20 bg-amber-500/[0.03] p-6">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-10 h-10 bg-amber-500/10 flex items-center justify-center">
              <Coins className="w-5 h-5 text-amber-400" />
            </div>
            <span className="text-[10px] font-mono text-amber-400/60 uppercase tracking-wider">Yield Revenue</span>
          </div>
          <div className="text-4xl font-bold text-white font-mono tracking-tight">
            ${data.yield_revenue_month.toFixed(0)}
          </div>
          <div className="text-xs text-white/40 font-mono mt-2">This month (30%)</div>
        </div>
      </div>

      {/* Tier Breakdown */}
      <div className="border border-white/10 bg-[#0a0a0a]">
        <div className="px-6 py-4 border-b border-white/10">
          <h3 className="text-sm font-bold text-white uppercase tracking-wider">Subscription Breakdown</h3>
        </div>
        <div className="divide-y divide-white/[0.06]">
          {/* Tycoon */}
          <div className="px-6 py-4 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-amber-500/10 border border-amber-500/20 flex items-center justify-center">
                <Crown className="w-6 h-6 text-amber-400" />
              </div>
              <div>
                <p className="text-sm font-bold text-white">Tycoon</p>
                <p className="text-xs text-white/40 font-mono">$29/month</p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-2xl font-bold text-white font-mono">{data.tier_breakdown.tycoon.count}</p>
              <p className="text-xs text-amber-400 font-mono">${data.tier_breakdown.tycoon.revenue}/mo</p>
            </div>
          </div>

          {/* Trader */}
          <div className="px-6 py-4 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-accent/10 border border-accent/20 flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-accent" />
              </div>
              <div>
                <p className="text-sm font-bold text-white">Trader</p>
                <p className="text-xs text-white/40 font-mono">$9/month</p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-2xl font-bold text-white font-mono">{data.tier_breakdown.trader.count}</p>
              <p className="text-xs text-accent font-mono">${data.tier_breakdown.trader.revenue}/mo</p>
            </div>
          </div>

          {/* Scout */}
          <div className="px-6 py-4 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-white/5 border border-white/10 flex items-center justify-center">
                <Zap className="w-6 h-6 text-white/40" />
              </div>
              <div>
                <p className="text-sm font-bold text-white">Scout</p>
                <p className="text-xs text-white/40 font-mono">Free</p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-2xl font-bold text-white font-mono">{data.tier_breakdown.scout.count}</p>
              <p className="text-xs text-white/30 font-mono">$0/mo</p>
            </div>
          </div>
        </div>
      </div>

      {/* Growth & Churn */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* New This Week */}
        <div className="border border-white/10 bg-white/[0.02] p-5">
          <div className="flex items-center gap-2 mb-2">
            <ArrowUpRight className="w-4 h-4 text-accent" />
            <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">New This Week</span>
          </div>
          <p className="text-3xl font-bold text-accent font-mono">{data.new_subscriptions.week}</p>
          <p className="text-xs text-white/30 font-mono mt-1">paid subscriptions</p>
        </div>

        {/* New This Month */}
        <div className="border border-white/10 bg-white/[0.02] p-5">
          <div className="flex items-center gap-2 mb-2">
            <TrendingUp className="w-4 h-4 text-blue-400" />
            <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">New This Month</span>
          </div>
          <p className="text-3xl font-bold text-blue-400 font-mono">{data.new_subscriptions.month}</p>
          <p className="text-xs text-white/30 font-mono mt-1">paid subscriptions</p>
        </div>

        {/* Churn */}
        <div className="border border-white/10 bg-white/[0.02] p-5">
          <div className="flex items-center gap-2 mb-2">
            <ArrowDownRight className="w-4 h-4 text-rose-400" />
            <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Churned This Month</span>
          </div>
          <p className="text-3xl font-bold text-rose-400 font-mono">{data.churn.month}</p>
          <p className="text-xs text-white/30 font-mono mt-1">cancelled</p>
        </div>
      </div>

      {/* Total Revenue Summary */}
      <div className="border border-white/10 bg-gradient-to-r from-white/[0.02] to-transparent p-6">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider mb-1">Total Monthly Revenue</p>
            <p className="text-xs text-white/30 font-mono">Subscriptions + Yield (30%)</p>
          </div>
          <div className="text-right">
            <p className="text-4xl font-bold text-white font-mono">${data.total_revenue_month.toLocaleString()}</p>
            <p className="text-xs text-white/40 font-mono mt-1">
              ${(data.total_revenue_month * 12).toLocaleString()} projected ARR
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}

