'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'

interface DashboardData {
  mrr: number
  totalSubscribers: number
  launchProgress: number
  nextTasks: { id: string; title: string; phase: number; status: string }[]
  tiers: { id: string; tierNumber: number; name: string; price: number; subscriberCount: number }[]
  recentActivity: { id: string; action: string; entity: string; details: string | null; createdAt: string; user: { name: string } }[]
  latestMetric: { quowavyFollowers: number; kevinthevpFollowers: number; oskvlabsFollowers: number; discordMembersFree: number; discordMembersPaid: number } | null
}

export default function DashboardPage() {
  const [data, setData] = useState<DashboardData | null>(null)
  const [loading, setLoading] = useState(true)
  const router = useRouter()

  useEffect(() => {
    fetch('/api/dashboard')
      .then(res => {
        if (res.status === 401) { router.push('/login'); return null }
        return res.json()
      })
      .then(d => { if (d) setData(d); setLoading(false) })
      .catch(() => setLoading(false))
  }, [router])

  if (loading) return <div className="flex items-center justify-center h-full"><div className="text-brand-muted">Loading...</div></div>
  if (!data) return null

  const statCards = [
    { label: 'Monthly Recurring Revenue', value: `$${data.mrr.toLocaleString()}`, sub: 'MRR', color: 'text-green-400', bg: 'bg-green-400/10', border: 'border-green-400/20' },
    { label: 'Total Subscribers', value: data.totalSubscribers.toString(), sub: 'across all tiers', color: 'text-brand-accent', bg: 'bg-brand-accent/10', border: 'border-brand-accent/20' },
    { label: 'Launch Progress', value: `${data.launchProgress}%`, sub: `${data.nextTasks.length} tasks remaining`, color: 'text-purple-400', bg: 'bg-purple-400/10', border: 'border-purple-400/20' },
    { label: 'Discord Members', value: data.latestMetric ? (data.latestMetric.discordMembersFree + data.latestMetric.discordMembersPaid).toString() : '0', sub: data.latestMetric ? `${data.latestMetric.discordMembersPaid} paid` : 'No data yet', color: 'text-amber-400', bg: 'bg-amber-400/10', border: 'border-amber-400/20' },
  ]

  return (
    <div className="max-w-7xl mx-auto space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-brand-text">Dashboard</h1>
        <p className="text-brand-muted text-sm mt-1">OSKV Labs launch overview</p>
      </div>

      {/* Stat Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map(card => (
          <div key={card.label} className={`${card.bg} border ${card.border} rounded-xl p-5`}>
            <p className="text-xs font-medium text-brand-muted uppercase tracking-wider">{card.label}</p>
            <p className={`text-3xl font-bold mt-2 ${card.color}`}>{card.value}</p>
            <p className="text-xs text-brand-muted mt-1">{card.sub}</p>
          </div>
        ))}
      </div>

      {/* Launch Progress Bar */}
      <div className="bg-brand-card border border-brand-border rounded-xl p-6">
        <div className="flex items-center justify-between mb-3">
          <h2 className="font-semibold text-brand-text">Launch Progress</h2>
          <span className="text-sm text-brand-muted">{data.launchProgress}%</span>
        </div>
        <div className="w-full bg-brand-bg rounded-full h-3">
          <div
            className="bg-gradient-to-r from-brand-accent to-purple-500 h-3 rounded-full transition-all duration-500"
            style={{ width: `${data.launchProgress}%` }}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Next Tasks */}
        <div className="bg-brand-card border border-brand-border rounded-xl p-6">
          <h2 className="font-semibold text-brand-text mb-4">Next Up</h2>
          <div className="space-y-3">
            {data.nextTasks.map(task => (
              <div key={task.id} className="flex items-center gap-3 p-3 bg-brand-bg/50 rounded-lg border border-brand-border/50">
                <div className={`w-2 h-2 rounded-full shrink-0 ${task.status === 'in_progress' ? 'bg-amber-400' : 'bg-brand-border'}`} />
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-brand-text truncate">{task.title}</p>
                  <p className="text-xs text-brand-muted">Phase {task.phase}</p>
                </div>
                <span className={`text-xs px-2 py-0.5 rounded-full ${
                  task.status === 'in_progress' ? 'bg-amber-400/10 text-amber-400' : 'bg-brand-border/50 text-brand-muted'
                }`}>
                  {task.status === 'in_progress' ? 'In Progress' : 'To Do'}
                </span>
              </div>
            ))}
            {data.nextTasks.length === 0 && <p className="text-brand-muted text-sm">All tasks complete! 🎉</p>}
          </div>
        </div>

        {/* Tier Breakdown */}
        <div className="bg-brand-card border border-brand-border rounded-xl p-6">
          <h2 className="font-semibold text-brand-text mb-4">Tier Breakdown</h2>
          <div className="space-y-3">
            {data.tiers.map(tier => (
              <div key={tier.id} className="flex items-center justify-between p-3 bg-brand-bg/50 rounded-lg border border-brand-border/50">
                <div>
                  <p className="text-sm font-medium text-brand-text">{tier.name}</p>
                  <p className="text-xs text-brand-muted">{tier.price === 0 ? 'Free' : `$${tier.price}/mo`}</p>
                </div>
                <div className="text-right">
                  <p className="text-lg font-bold text-brand-accent">{tier.subscriberCount}</p>
                  <p className="text-xs text-brand-muted">subscribers</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="bg-brand-card border border-brand-border rounded-xl p-6 lg:col-span-2">
          <h2 className="font-semibold text-brand-text mb-4">Recent Activity</h2>
          <div className="space-y-2">
            {data.recentActivity.map(log => (
              <div key={log.id} className="flex items-center gap-3 py-2 border-b border-brand-border/30 last:border-0">
                <div className="w-7 h-7 rounded-full bg-brand-accent/10 flex items-center justify-center shrink-0">
                  <span className="text-xs font-bold text-brand-accent">{log.user.name[0]}</span>
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-brand-text">
                    <span className="font-medium">{log.user.name}</span>{' '}
                    <span className="text-brand-muted">{log.action}</span>{' '}
                    <span className="text-brand-text">{log.entity}</span>
                  </p>
                  {log.details && <p className="text-xs text-brand-muted truncate">{log.details}</p>}
                </div>
                <span className="text-xs text-brand-muted shrink-0">
                  {new Date(log.createdAt).toLocaleDateString()}
                </span>
              </div>
            ))}
            {data.recentActivity.length === 0 && <p className="text-brand-muted text-sm">No activity yet</p>}
          </div>
        </div>
      </div>
    </div>
  )
}
