'use client'

import { useEffect, useState } from 'react'
import { api } from '@/lib/api'
import {
  DollarSign,
  TrendingUp,
  TrendingDown,
  Users,
  Crown,
  Zap,
  RefreshCw,
  Loader2,
  ArrowUpRight,
  ArrowDownRight,
  Coins,
  Target,
  Activity,
  BarChart3,
} from 'lucide-react'
import clsx from 'clsx'
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  ComposedChart,
} from 'recharts'

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
}

interface HistoryData {
  monthly_data: Array<{
    month: string
    mrr: number
    arr: number
    paying_customers: number
    scout: number
    trader: number
    tycoon: number
    new_subscriptions: number
    churn: number
  }>
  metrics: {
    mrr_growth_percent: number
    arpu: number
    ltv: number
    total_customers: number
  }
  timestamp: string
}

// Custom colors
const COLORS = {
  primary: '#ef4444',
  accent: '#22c55e',
  amber: '#f59e0b',
  blue: '#3b82f6',
  rose: '#f43f5e',
}

const TIER_COLORS = {
  scout: '#6b7280',
  trader: '#22c55e',
  tycoon: '#f59e0b',
}

// Custom tooltip
const CustomTooltip = ({ active, payload, label }: any) => {
  if (!active || !payload || !payload.length) return null
  
  return (
    <div className="bg-[#0a0a0a] border border-white/10 p-3 shadow-xl">
      <p className="text-xs font-mono text-white/60 mb-2">{label}</p>
      {payload.map((entry: any, index: number) => (
        <div key={index} className="flex items-center gap-2 text-sm">
          <div className="w-2 h-2 rounded-full" style={{ backgroundColor: entry.color }} />
          <span className="text-white/80">{entry.name}:</span>
          <span className="font-mono font-bold text-white">
            {entry.dataKey === 'mrr' ? `$${entry.value.toLocaleString()}` : entry.value}
          </span>
        </div>
      ))}
    </div>
  )
}

export function EarningsTab() {
  const [data, setData] = useState<EarningsData | null>(null)
  const [history, setHistory] = useState<HistoryData | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [activeChart, setActiveChart] = useState<'revenue' | 'growth'>('revenue')

  const loadData = async () => {
    try {
      const [earnings, earningsHistory] = await Promise.all([
        api.getAdminEarnings(),
        api.getAdminEarningsHistory(12),
      ])
      setData(earnings)
      setHistory(earningsHistory)
    } 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-8 h-8 text-red-400 animate-spin" />
      </div>
    )
  }

  if (!data || !history) {
    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>
    )
  }

  // Calculate net growth
  const netGrowth = data.new_subscriptions.month - data.churn.month

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-white flex items-center gap-2">
            <Activity className="w-5 h-5 text-red-400" />
            Revenue Dashboard
          </h2>
          <p className="text-xs text-white/30 font-mono mt-1">
            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 KPIs - 6 Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
        {/* MRR */}
        <div className="relative overflow-hidden border border-red-500/30 bg-gradient-to-br from-red-500/10 to-transparent p-4">
          <div className="flex items-center gap-2 mb-1">
            <DollarSign className="w-4 h-4 text-red-400" />
            <span className="text-[10px] font-mono text-red-400/80 uppercase">MRR</span>
          </div>
          <div className="text-2xl font-bold text-white font-mono">
            ${data.mrr.toLocaleString()}
          </div>
          {history.metrics.mrr_growth_percent !== 0 && (
            <div className={clsx(
              "flex items-center gap-1 mt-1 text-[10px] font-mono",
              history.metrics.mrr_growth_percent > 0 ? "text-green-400" : "text-rose-400"
            )}>
              {history.metrics.mrr_growth_percent > 0 ? <ArrowUpRight className="w-3 h-3" /> : <ArrowDownRight className="w-3 h-3" />}
              {Math.abs(history.metrics.mrr_growth_percent)}%
            </div>
          )}
        </div>

        {/* ARR */}
        <div className="relative overflow-hidden border border-green-500/30 bg-gradient-to-br from-green-500/10 to-transparent p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp className="w-4 h-4 text-green-400" />
            <span className="text-[10px] font-mono text-green-400/80 uppercase">ARR</span>
          </div>
          <div className="text-2xl font-bold text-white font-mono">
            ${data.arr.toLocaleString()}
          </div>
          <div className="text-[10px] text-white/40 font-mono mt-1">projected</div>
        </div>

        {/* Paying Customers */}
        <div className="border border-white/10 bg-white/[0.02] p-4">
          <div className="flex items-center gap-2 mb-1">
            <Users className="w-4 h-4 text-blue-400" />
            <span className="text-[10px] font-mono text-white/40 uppercase">Paying</span>
          </div>
          <div className="text-2xl font-bold text-white font-mono">
            {data.paying_customers}
          </div>
          <div className="text-[10px] text-white/40 font-mono mt-1">customers</div>
        </div>

        {/* ARPU */}
        <div className="border border-white/10 bg-white/[0.02] p-4">
          <div className="flex items-center gap-2 mb-1">
            <Target className="w-4 h-4 text-purple-400" />
            <span className="text-[10px] font-mono text-white/40 uppercase">ARPU</span>
          </div>
          <div className="text-2xl font-bold text-white font-mono">
            ${history.metrics.arpu.toFixed(0)}
          </div>
          <div className="text-[10px] text-white/40 font-mono mt-1">LTV: ${history.metrics.ltv.toFixed(0)}</div>
        </div>

        {/* Net Growth */}
        <div className={clsx(
          "border p-4",
          netGrowth >= 0 ? "border-green-500/20 bg-green-500/[0.03]" : "border-rose-500/20 bg-rose-500/[0.03]"
        )}>
          <div className="flex items-center gap-2 mb-1">
            {netGrowth >= 0 ? <TrendingUp className="w-4 h-4 text-green-400" /> : <TrendingDown className="w-4 h-4 text-rose-400" />}
            <span className="text-[10px] font-mono text-white/40 uppercase">Net Growth</span>
          </div>
          <div className={clsx("text-2xl font-bold font-mono", netGrowth >= 0 ? "text-green-400" : "text-rose-400")}>
            {netGrowth >= 0 ? '+' : ''}{netGrowth}
          </div>
          <div className="text-[10px] text-white/40 font-mono mt-1">this month</div>
        </div>

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

      {/* Chart Section */}
      <div className="border border-white/10 bg-[#0a0a0a]">
        <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <BarChart3 className="w-5 h-5 text-red-400" />
            <h3 className="text-sm font-bold text-white uppercase tracking-wider">Trend</h3>
          </div>
          <div className="flex gap-1">
            {(['revenue', 'growth'] as const).map((chart) => (
              <button
                key={chart}
                onClick={() => setActiveChart(chart)}
                className={clsx(
                  "px-3 py-1.5 text-xs font-mono uppercase transition-all",
                  activeChart === chart ? "bg-white/10 text-white" : "text-white/40 hover:text-white hover:bg-white/5"
                )}
              >
                {chart === 'revenue' ? 'MRR' : 'Growth'}
              </button>
            ))}
          </div>
        </div>
        <div className="p-6 h-72">
          <ResponsiveContainer width="100%" height="100%">
            {activeChart === 'revenue' ? (
              <AreaChart data={history.monthly_data}>
                <defs>
                  <linearGradient id="mrrGradient" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor={COLORS.primary} stopOpacity={0.3}/>
                    <stop offset="95%" stopColor={COLORS.primary} stopOpacity={0}/>
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                <XAxis dataKey="month" tick={{ fill: 'rgba(255,255,255,0.4)', fontSize: 10 }} axisLine={{ stroke: 'rgba(255,255,255,0.1)' }} />
                <YAxis tick={{ fill: 'rgba(255,255,255,0.4)', fontSize: 10 }} axisLine={{ stroke: 'rgba(255,255,255,0.1)' }} tickFormatter={(v) => `$${v}`} />
                <Tooltip content={<CustomTooltip />} />
                <Area type="monotone" dataKey="mrr" name="MRR" stroke={COLORS.primary} strokeWidth={2} fill="url(#mrrGradient)" />
              </AreaChart>
            ) : (
              <ComposedChart data={history.monthly_data}>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                <XAxis dataKey="month" tick={{ fill: 'rgba(255,255,255,0.4)', fontSize: 10 }} axisLine={{ stroke: 'rgba(255,255,255,0.1)' }} />
                <YAxis tick={{ fill: 'rgba(255,255,255,0.4)', fontSize: 10 }} axisLine={{ stroke: 'rgba(255,255,255,0.1)' }} />
                <Tooltip content={<CustomTooltip />} />
                <Legend wrapperStyle={{ paddingTop: '10px' }} formatter={(v) => <span className="text-white/60 text-xs font-mono">{v}</span>} />
                <Bar dataKey="new_subscriptions" name="New" fill={COLORS.accent} radius={[4, 4, 0, 0]} />
                <Bar dataKey="churn" name="Churned" fill={COLORS.rose} radius={[4, 4, 0, 0]} />
                <Line type="monotone" dataKey="paying_customers" name="Total" stroke={COLORS.blue} strokeWidth={2} dot={{ fill: COLORS.blue, r: 3 }} />
              </ComposedChart>
            )}
          </ResponsiveContainer>
        </div>
      </div>

      {/* Subscription Breakdown - Clean Table */}
      <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">Subscriptions</h3>
        </div>
        <div className="divide-y divide-white/[0.06]">
          {/* Tycoon */}
          <div className="px-6 py-3 flex items-center gap-4 hover:bg-white/[0.02] transition-colors">
            <div className="w-10 h-10 bg-amber-500/10 border border-amber-500/20 flex items-center justify-center flex-shrink-0">
              <Crown className="w-5 h-5 text-amber-400" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-bold text-white">Tycoon</p>
              <p className="text-xs text-white/40 font-mono">$29/mo</p>
            </div>
            <div className="text-right">
              <p className="text-xl font-bold text-white font-mono">{data.tier_breakdown.tycoon.count}</p>
            </div>
            <div className="w-24 text-right">
              <p className="text-sm font-bold text-amber-400 font-mono">${data.tier_breakdown.tycoon.revenue}</p>
              <p className="text-[10px] text-white/30 font-mono">/month</p>
            </div>
            <div className="w-24 h-1.5 bg-white/5 rounded-full overflow-hidden">
              <div 
                className="h-full bg-amber-400 rounded-full"
                style={{ width: `${data.mrr > 0 ? (data.tier_breakdown.tycoon.revenue / data.mrr) * 100 : 0}%` }}
              />
            </div>
          </div>

          {/* Trader */}
          <div className="px-6 py-3 flex items-center gap-4 hover:bg-white/[0.02] transition-colors">
            <div className="w-10 h-10 bg-green-500/10 border border-green-500/20 flex items-center justify-center flex-shrink-0">
              <TrendingUp className="w-5 h-5 text-green-400" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-bold text-white">Trader</p>
              <p className="text-xs text-white/40 font-mono">$9/mo</p>
            </div>
            <div className="text-right">
              <p className="text-xl font-bold text-white font-mono">{data.tier_breakdown.trader.count}</p>
            </div>
            <div className="w-24 text-right">
              <p className="text-sm font-bold text-green-400 font-mono">${data.tier_breakdown.trader.revenue}</p>
              <p className="text-[10px] text-white/30 font-mono">/month</p>
            </div>
            <div className="w-24 h-1.5 bg-white/5 rounded-full overflow-hidden">
              <div 
                className="h-full bg-green-400 rounded-full"
                style={{ width: `${data.mrr > 0 ? (data.tier_breakdown.trader.revenue / data.mrr) * 100 : 0}%` }}
              />
            </div>
          </div>

          {/* Scout */}
          <div className="px-6 py-3 flex items-center gap-4 hover:bg-white/[0.02] transition-colors">
            <div className="w-10 h-10 bg-white/5 border border-white/10 flex items-center justify-center flex-shrink-0">
              <Zap className="w-5 h-5 text-white/40" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-bold text-white">Scout</p>
              <p className="text-xs text-white/40 font-mono">Free</p>
            </div>
            <div className="text-right">
              <p className="text-xl font-bold text-white font-mono">{data.tier_breakdown.scout.count}</p>
            </div>
            <div className="w-24 text-right">
              <p className="text-sm font-bold text-white/30 font-mono">$0</p>
              <p className="text-[10px] text-white/30 font-mono">/month</p>
            </div>
            <div className="w-24 h-1.5 bg-white/5 rounded-full overflow-hidden">
              <div className="h-full bg-white/20 rounded-full" style={{ width: '0%' }} />
            </div>
          </div>
        </div>

        {/* Total Row */}
        <div className="px-6 py-4 bg-white/[0.02] border-t border-white/10 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="text-xs font-mono text-white/40 uppercase">Total Monthly</span>
          </div>
          <div className="text-2xl font-bold text-white font-mono">
            ${data.total_revenue_month.toLocaleString()}
          </div>
        </div>
      </div>
    </div>
  )
}
