'use client'

import { useState, useEffect, useCallback } from 'react'
import Header from '@/components/layout/Header'
import { ArrowPathIcon, SignalIcon } from '@heroicons/react/24/outline'

type Session = {
  id: number
  ip: string | null
  lastSeen: string
  createdAt: string
  user: { id: number; name: string; email: string; role: string }
}

function timeDiff(date: string) {
  const diff = Math.floor((Date.now() - new Date(date).getTime()) / 1000)
  if (diff < 60) return `hace ${diff}s`
  if (diff < 3600) return `hace ${Math.floor(diff / 60)}m`
  return `hace ${Math.floor(diff / 3600)}h`
}

function statusDot(lastSeen: string) {
  const diff = (Date.now() - new Date(lastSeen).getTime()) / 1000
  if (diff < 90) return 'bg-green-500'
  if (diff < 300) return 'bg-yellow-400'
  return 'bg-gray-300'
}

const roleBadge: Record<string, string> = {
  SUPER_ADMIN: 'bg-red-100 text-red-700',
  ADMIN: 'bg-orange-100 text-orange-700',
  EDITOR: 'bg-blue-100 text-blue-700',
  GERENCIAL: 'bg-purple-100 text-purple-700',
  VISUALIZADOR: 'bg-gray-100 text-gray-600',
}

export default function MonitorPage() {
  const [sessions, setSessions] = useState<Session[]>([])
  const [totalUsers, setTotalUsers] = useState(0)
  const [loading, setLoading] = useState(true)
  const [lastRefresh, setLastRefresh] = useState(new Date())

  const load = useCallback(async () => {
    setLoading(true)
    const res = await fetch('/api/admin/monitor')
    const data = await res.json()
    setSessions(data.sessions)
    setTotalUsers(data.totalUsers)
    setLastRefresh(new Date())
    setLoading(false)
  }, [])

  useEffect(() => {
    load()
    const id = setInterval(load, 30 * 1000)
    return () => clearInterval(id)
  }, [load])

  return (
    <div>
      <Header title="Monitor de Usuarios" />
      <div className="p-6 space-y-4">
        <div className="grid grid-cols-2 gap-4 max-w-sm">
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 text-center">
            <p className="text-3xl font-bold text-green-600">{sessions.length}</p>
            <p className="text-xs text-gray-400 mt-1">Activos (últimos 10 min)</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 text-center">
            <p className="text-3xl font-bold text-gray-700">{totalUsers}</p>
            <p className="text-xs text-gray-400 mt-1">Usuarios totales</p>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-4 py-3 border-b border-gray-50 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <SignalIcon className="w-4 h-4 text-green-500" />
              <span className="text-xs font-medium text-gray-600">Sesiones en línea</span>
            </div>
            <div className="flex items-center gap-3">
              <span className="text-xs text-gray-400">
                Actualizado: {lastRefresh.toLocaleTimeString('es-CL')}
              </span>
              <button
                onClick={load}
                disabled={loading}
                className="p-1.5 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-600 disabled:opacity-40"
                title="Actualizar"
              >
                <ArrowPathIcon className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
              </button>
            </div>
          </div>

          {loading && sessions.length === 0 ? (
            <p className="text-gray-400 text-sm p-6">Cargando...</p>
          ) : sessions.length === 0 ? (
            <div className="text-center py-12">
              <SignalIcon className="w-8 h-8 text-gray-200 mx-auto mb-2" />
              <p className="text-gray-400 text-sm">Sin usuarios activos en este momento</p>
            </div>
          ) : (
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-100">
                <tr>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Estado</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Usuario</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Rol</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">IP</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Última actividad</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {sessions.map((s) => (
                  <tr key={s.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3">
                      <span className={`w-2.5 h-2.5 rounded-full inline-block ${statusDot(s.lastSeen)}`} />
                    </td>
                    <td className="px-4 py-3">
                      <p className="font-medium text-gray-800">{s.user.name}</p>
                      <p className="text-gray-400 text-xs">{s.user.email}</p>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${roleBadge[s.user.role] ?? 'bg-gray-100 text-gray-600'}`}>
                        {s.user.role}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 text-xs font-mono">{s.ip ?? '—'}</td>
                    <td className="px-4 py-3 text-gray-500 text-xs">{timeDiff(s.lastSeen)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        <div className="flex gap-4 text-xs text-gray-400">
          <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-green-500" /> Activo (&lt;90s)</span>
          <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-yellow-400" /> Inactivo (&lt;5min)</span>
          <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-gray-300" /> Desconectado</span>
        </div>
      </div>
    </div>
  )
}
