import React, { useEffect, useState, useCallback } from 'react'
import { useRouter } from 'next/router'
import { motion } from 'framer-motion'
import {
  RadialBarChart,
  RadialBar,
  PolarAngleAxis,
} from 'recharts'
import {
  Cpu,
  MemoryStick,
  HardDrive,
  Clock,
  Wifi,
  Users,
  Activity,
  RefreshCw,
  ShieldCheck,
  ArrowLeftFromLine,
} from 'lucide-react'
import Link from 'next/link'
import { useAuth } from '@/context/AuthContext'
import { api } from '@/services/chatApiService'
import { PageHeader, Card } from '@/components/ui'

interface Metrics {
  cpu: { percent: number }
  ram: { total: number; used: number; percent: number }
  disk: { total: number; used: number; percent: number }
  uptime: number
  connectedInstances: number
  totalUsers: number
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B'
  const gb = bytes / 1024 / 1024 / 1024
  return gb >= 1 ? `${gb.toFixed(1)} GB` : `${(bytes / 1024 / 1024).toFixed(0)} MB`
}

function formatUptime(seconds: number): string {
  const d = Math.floor(seconds / 86400)
  const h = Math.floor((seconds % 86400) / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (d > 0) return `${d}d ${h}h ${m}m`
  if (h > 0) return `${h}h ${m}m`
  return `${m}m`
}

function getColor(percent: number): string {
  if (percent >= 90) return '#ef4444'
  if (percent >= 70) return '#f97316'
  return '#3b82f6'
}

interface GaugeProps {
  label: string
  percent: number
  icon: React.ElementType
  sublabel: string
  delay?: number
}

function GaugeCard({ label, percent, icon: Icon, sublabel, delay = 0 }: GaugeProps) {
  const color = getColor(percent)
  const data = [{ value: percent, fill: color }]

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.4 }}
    >
      <Card
        variant="glass"
        padding="p-6"
        className="rounded-3xl flex flex-col items-center gap-2 relative overflow-hidden group hover:border-white/10 transition-colors"
      >
        <div
          className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none"
          style={{ background: `radial-gradient(circle at 50% 0%, ${color}15 0%, transparent 70%)` }}
        />

        <div className="flex items-center gap-2 w-full mb-1">
          <Icon size={16} style={{ color }} />
          <span className="text-xs font-bold text-slate-400 uppercase tracking-widest">{label}</span>
        </div>

        <div className="relative w-48 h-48">
          <RadialBarChart
            width={192}
            height={192}
            cx="50%"
            cy="50%"
            innerRadius="72%"
            outerRadius="90%"
            startAngle={220}
            endAngle={-40}
            data={data}
          >
            <PolarAngleAxis
              type="number"
              domain={[0, 100]}
              angleAxisId={0}
              tick={false}
            />
            <RadialBar
              background={{ fill: 'rgba(255,255,255,0.04)' }}
              dataKey="value"
              angleAxisId={0}
              cornerRadius={8}
            />
          </RadialBarChart>

          <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
            <span className="text-3xl font-black text-white tabular-nums" style={{ color }}>
              {percent}%
            </span>
          </div>
        </div>

        <p className="text-xs text-slate-500 font-mono">{sublabel}</p>
      </Card>
    </motion.div>
  )
}

interface StatItemProps {
  icon: React.ElementType
  label: string
  value: string
  color: string
  delay?: number
}

function StatItem({ icon: Icon, label, value, color, delay = 0 }: StatItemProps) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.35 }}
    >
      <Card
        variant="glass"
        padding="p-5"
        className="rounded-2xl flex items-center gap-4 hover:border-white/10 transition-colors"
      >
        <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${color}18` }}>
          <Icon size={20} style={{ color }} />
        </div>
        <div>
          <p className="text-xs text-slate-500 uppercase tracking-widest font-bold">{label}</p>
          <p className="text-lg font-black text-white tabular-nums">{value}</p>
        </div>
      </Card>
    </motion.div>
  )
}

export default function AdminDashboard() {
  const { user, loading } = useAuth()
  const router = useRouter()
  const [metrics, setMetrics] = useState<Metrics | null>(null)
  const [fetching, setFetching] = useState(false)
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null)

  const fetchMetrics = useCallback(async () => {
    setFetching(true)
    try {
      const { data } = await api.get('/api/admin/metrics')
      setMetrics(data)
      setLastUpdate(new Date())
    } catch {
      // silencioso — mantém últimos dados
    } finally {
      setFetching(false)
    }
  }, [])

  // Guard: redireciona não-admin
  useEffect(() => {
    if (!loading && user?.role !== 'admin') {
      router.replace('/inbox')
    }
  }, [loading, user, router])

  // Coleta inicial + polling a cada 3s
  useEffect(() => {
    if (user?.role !== 'admin') return
    fetchMetrics()
    const id = setInterval(fetchMetrics, 3000)
    return () => clearInterval(id)
  }, [user, fetchMetrics])

  if (loading || user?.role !== 'admin') return null

  return (
    <div className="min-h-screen bg-surface p-6 lg:p-10 font-sans">
      <PageHeader
        icon={ShieldCheck}
        title="Admin Monitor"
        subtitle="Métricas do servidor em tempo real"
        actions={
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2 px-3 py-1.5 rounded-xl bg-white/5 border border-white/5">
              <Activity size={14} className={fetching ? 'text-brand-400 animate-pulse' : 'text-green-400'} />
              <span className="text-xs font-bold text-slate-400">
                {lastUpdate ? `Atualizado ${lastUpdate.toLocaleTimeString('pt-BR')}` : 'Aguardando...'}
              </span>
            </div>
            <button
              onClick={fetchMetrics}
              className="p-2 rounded-xl bg-white/5 border border-white/5 hover:border-brand-500/30 hover:text-brand-400 text-slate-400 transition-all"
              title="Atualizar agora"
            >
              <RefreshCw size={15} className={fetching ? 'animate-spin' : ''} />
            </button>
            <Link href="/dashboard">
              <div className="flex items-center gap-2 px-3 py-1.5 rounded-xl border cursor-pointer transition-all group
                bg-white/[0.04] border-white/10 hover:bg-brand-500/10 hover:border-brand-500/30 text-slate-400 hover:text-brand-300">
                <ArrowLeftFromLine size={14} className="shrink-0 transition-transform group-hover:-translate-x-0.5" />
                <span className="text-xs font-bold hidden sm:inline">Sair do Admin</span>
              </div>
            </Link>
          </div>
        }
      />

      {/* Gauges circulares */}
      {metrics ? (
        <>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <GaugeCard
              label="CPU"
              percent={metrics.cpu.percent}
              icon={Cpu}
              sublabel="Carga do processador"
              delay={0}
            />
            <GaugeCard
              label="RAM"
              percent={metrics.ram.percent}
              icon={MemoryStick}
              sublabel={`${formatBytes(metrics.ram.used)} / ${formatBytes(metrics.ram.total)}`}
              delay={0.1}
            />
            <GaugeCard
              label="Disco"
              percent={metrics.disk.percent}
              icon={HardDrive}
              sublabel={`${formatBytes(metrics.disk.used)} / ${formatBytes(metrics.disk.total)}`}
              delay={0.2}
            />
          </div>

          {/* Stats */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <StatItem
              icon={Clock}
              label="Uptime"
              value={formatUptime(metrics.uptime)}
              color="#a78bfa"
              delay={0.3}
            />
            <StatItem
              icon={Wifi}
              label="Instâncias Conectadas"
              value={String(metrics.connectedInstances)}
              color="#34d399"
              delay={0.35}
            />
            <StatItem
              icon={Users}
              label="Total de Usuários"
              value={String(metrics.totalUsers)}
              color="#60a5fa"
              delay={0.4}
            />
          </div>
        </>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-72 rounded-3xl bg-white/5 animate-pulse" />
          ))}
        </div>
      )}
    </div>
  )
}
