import { useState, useEffect } from 'react'
import { adminApi } from '@/api'
import type { DashboardStats } from '@/types'
import { Users, Trophy, Gamepad2, UserCheck, Ban, Activity, TrendingUp } from 'lucide-react'

const ACTION_LABELS: Record<string, string> = {
  user_ban: 'Бан пользователя',
  user_unban: 'Разбан пользователя',
  user_role_change: 'Изменение роли',
  marathon_force_finish: 'Принудительное завершение',
  marathon_delete: 'Удаление марафона',
  content_update: 'Обновление контента',
  broadcast_all: 'Рассылка всем',
  broadcast_marathon: 'Рассылка марафону',
  admin_login: 'Вход админа',
  admin_2fa_success: '2FA успех',
  admin_2fa_fail: '2FA неудача',
}

const ACTION_COLORS: Record<string, string> = {
  user_ban: 'text-red-400',
  user_unban: 'text-green-400',
  user_role_change: 'text-accent-400',
  marathon_force_finish: 'text-orange-400',
  marathon_delete: 'text-red-400',
  content_update: 'text-neon-400',
  broadcast_all: 'text-pink-400',
  broadcast_marathon: 'text-pink-400',
  admin_login: 'text-blue-400',
  admin_2fa_success: 'text-green-400',
  admin_2fa_fail: 'text-red-400',
}

function StatCard({
  icon: Icon,
  label,
  value,
  gradient,
  glowColor
}: {
  icon: typeof Users
  label: string
  value: number
  gradient: string
  glowColor: string
}) {
  return (
    <div className={`glass rounded-xl p-5 border border-dark-600 hover:border-dark-500 transition-all duration-300 hover:shadow-[0_0_20px_${glowColor}]`}>
      <div className="flex items-center gap-4">
        <div className={`p-3 rounded-xl ${gradient} shadow-lg`}>
          <Icon className="w-6 h-6 text-white" />
        </div>
        <div>
          <p className="text-sm text-gray-400">{label}</p>
          <p className="text-2xl font-bold text-white">{value.toLocaleString()}</p>
        </div>
      </div>
    </div>
  )
}

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleString('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

export function AdminDashboardPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [loading, setLoading] = useState(true)

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

  const loadDashboard = async () => {
    try {
      const data = await adminApi.getDashboard()
      setStats(data)
    } catch (err) {
      console.error('Failed to load dashboard:', err)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-2 border-accent-500 border-t-transparent" />
      </div>
    )
  }

  if (!stats) {
    return (
      <div className="text-center text-gray-400 py-12">
        Не удалось загрузить данные
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="p-2 rounded-lg bg-accent-500/20 border border-accent-500/30">
          <TrendingUp className="w-6 h-6 text-accent-400" />
        </div>
        <h1 className="text-2xl font-bold text-white">Дашборд</h1>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <StatCard
          icon={Users}
          label="Всего пользователей"
          value={stats.users_count}
          gradient="bg-gradient-to-br from-blue-500 to-blue-600"
          glowColor="rgba(59,130,246,0.15)"
        />
        <StatCard
          icon={Ban}
          label="Заблокировано"
          value={stats.banned_users_count}
          gradient="bg-gradient-to-br from-red-500 to-red-600"
          glowColor="rgba(239,68,68,0.15)"
        />
        <StatCard
          icon={Trophy}
          label="Всего марафонов"
          value={stats.marathons_count}
          gradient="bg-gradient-to-br from-accent-500 to-pink-500"
          glowColor="rgba(139,92,246,0.15)"
        />
        <StatCard
          icon={Activity}
          label="Активных марафонов"
          value={stats.active_marathons_count}
          gradient="bg-gradient-to-br from-green-500 to-emerald-600"
          glowColor="rgba(34,197,94,0.15)"
        />
        <StatCard
          icon={Gamepad2}
          label="Всего игр"
          value={stats.games_count}
          gradient="bg-gradient-to-br from-orange-500 to-amber-500"
          glowColor="rgba(249,115,22,0.15)"
        />
        <StatCard
          icon={UserCheck}
          label="Участий в марафонах"
          value={stats.total_participations}
          gradient="bg-gradient-to-br from-neon-500 to-cyan-500"
          glowColor="rgba(34,211,238,0.15)"
        />
      </div>

      {/* Recent Logs */}
      <div className="glass rounded-xl border border-dark-600 overflow-hidden">
        <div className="p-4 border-b border-dark-600">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2">
            <Activity className="w-5 h-5 text-accent-400" />
            Последние действия
          </h2>
        </div>
        <div className="p-4">
          {stats.recent_logs.length === 0 ? (
            <p className="text-gray-400 text-center py-4">Нет записей</p>
          ) : (
            <div className="space-y-3">
              {stats.recent_logs.map((log) => (
                <div
                  key={log.id}
                  className="flex items-start justify-between p-4 bg-dark-700/50 hover:bg-dark-700 rounded-xl border border-dark-600 transition-colors"
                >
                  <div>
                    <p className={`font-medium ${ACTION_COLORS[log.action] || 'text-white'}`}>
                      {ACTION_LABELS[log.action] || log.action}
                    </p>
                    <p className="text-sm text-gray-400 mt-1">
                      <span className="text-gray-500">Админ:</span> {log.admin_nickname}
                      <span className="text-gray-600 mx-2">•</span>
                      <span className="text-gray-500">{log.target_type}</span> #{log.target_id}
                    </p>
                    {log.details && (
                      <p className="text-xs text-gray-500 mt-2 font-mono bg-dark-800 rounded px-2 py-1 inline-block">
                        {JSON.stringify(log.details)}
                      </p>
                    )}
                  </div>
                  <span className="text-xs text-gray-500 whitespace-nowrap ml-4">
                    {formatDate(log.created_at)}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
