import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import Link from 'next/link'
import Header from '@/components/layout/Header'
import {
  NewspaperIcon, FolderIcon, MapIcon, CalendarIcon,
  UserGroupIcon, ChatBubbleLeftIcon, DocumentTextIcon,
  ArrowRightIcon, ClockIcon,
} from '@heroicons/react/24/outline'

function greeting(name: string) {
  const h = new Date().getHours()
  const saludo = h < 12 ? 'Buenos días' : h < 19 ? 'Buenas tardes' : 'Buenas noches'
  return `${saludo}, ${name.split(' ')[0]}`
}

function timeAgo(date: Date) {
  const diff = Math.floor((Date.now() - date.getTime()) / 1000)
  if (diff < 3600) return `hace ${Math.floor(diff / 60)}m`
  if (diff < 86400) return `hace ${Math.floor(diff / 3600)}h`
  if (diff < 86400 * 7) return `hace ${Math.floor(diff / 86400)}d`
  return date.toLocaleDateString('es-CL')
}

const STATUS_COLOR: Record<string, string> = {
  BORRADOR: 'bg-yellow-100 text-yellow-700',
  VIGENTE: 'bg-green-100 text-green-700',
  OBSOLETO: 'bg-gray-100 text-gray-500',
}
const TYPE_COLOR: Record<string, string> = {
  PROCEDIMIENTO: 'bg-blue-100 text-blue-700',
  DIAGRAMA: 'bg-purple-100 text-purple-700',
  REGISTRO: 'bg-orange-100 text-orange-700',
  POLITICA: 'bg-red-100 text-red-700',
  MANUAL: 'bg-indigo-100 text-indigo-700',
  OTRO: 'bg-gray-100 text-gray-600',
}

export default async function DashboardPage() {
  const session = await getServerSession(authOptions)
  const userName = session?.user?.name ?? 'Usuario'
  const role = (session?.user as { role?: string })?.role ?? ''
  const isAdmin = role === 'SUPER_ADMIN' || role === 'ADMIN'

  const [
    totalDocs, totalProcesses, publishedNews, totalUsers,
    latestNews, recentDocs, pendingSuggestions,
  ] = await Promise.all([
    prisma.document.count(),
    prisma.processNode.count(),
    prisma.news.count({ where: { published: true } }),
    prisma.user.count({ where: { active: true } }),
    prisma.news.findMany({
      where: { published: true },
      orderBy: { createdAt: 'desc' },
      take: 4,
      select: { id: true, title: true, createdAt: true, author: { select: { name: true } } },
    }),
    prisma.document.findMany({
      orderBy: { updatedAt: 'desc' },
      take: 5,
      select: {
        id: true, title: true, type: true, status: true, version: true, updatedAt: true,
        uploadedBy: { select: { name: true } },
      },
    }),
    isAdmin
      ? prisma.suggestion.count({ where: { status: 'PENDIENTE' } })
      : 0,
  ])

  const stats = [
    { label: 'Documentos', value: totalDocs, icon: FolderIcon, color: 'bg-amber-500', href: '/documentos' },
    { label: 'Procesos', value: totalProcesses, icon: MapIcon, color: 'bg-green-600', href: '/mapa-procesos' },
    { label: 'Noticias', value: publishedNews, icon: NewspaperIcon, color: 'bg-blue-500', href: '/noticias' },
    { label: 'Usuarios activos', value: totalUsers, icon: UserGroupIcon, color: 'bg-purple-500', href: isAdmin ? '/admin/usuarios' : '/directorio' },
  ]

  const quickLinks = [
    { href: '/noticias', label: 'Noticias', icon: NewspaperIcon, desc: 'Comunicados internos' },
    { href: '/documentos', label: 'Documentos', icon: DocumentTextIcon, desc: 'Políticas y procedimientos' },
    { href: '/mapa-procesos', label: 'Mapa de Procesos', icon: MapIcon, desc: 'Estructura de procesos' },
    { href: '/directorio', label: 'Directorio', icon: UserGroupIcon, desc: 'Contactos del equipo' },
    { href: '/calendario', label: 'Calendario', icon: CalendarIcon, desc: 'Eventos corporativos' },
    { href: '/sugerencias', label: 'Sugerencias / TI', icon: ChatBubbleLeftIcon, desc: 'Envía una solicitud' },
  ]

  return (
    <div>
      <Header title="Inicio" />
      <div className="p-6 space-y-6">

        {/* Saludo */}
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-gray-800">{greeting(userName)}</h2>
            <p className="text-gray-400 text-sm mt-0.5">
              {new Date().toLocaleDateString('es-CL', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
              {role && <span className="ml-2 px-2 py-0.5 bg-gray-100 text-gray-500 rounded-full text-xs font-medium">{role}</span>}
            </p>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {stats.map(({ label, value, icon: Icon, color, href }) => (
            <Link key={href} href={href} className="bg-white rounded-xl border border-gray-100 shadow-sm p-5 flex items-center gap-4 hover:shadow-md transition-shadow group">
              <div className={`${color} rounded-xl p-3 flex-shrink-0`}>
                <Icon className="w-6 h-6 text-white" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-800">{value}</p>
                <p className="text-xs text-gray-400 mt-0.5">{label}</p>
              </div>
            </Link>
          ))}
        </div>

        {/* Contenido principal */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

          {/* Últimas noticias — ocupa 2 cols */}
          <div className="lg:col-span-2 bg-white rounded-xl border border-gray-100 shadow-sm">
            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-50">
              <h3 className="font-semibold text-gray-700 text-sm">Últimas noticias</h3>
              <Link href="/noticias" className="flex items-center gap-1 text-xs text-green-600 hover:text-green-800 font-medium">
                Ver todas <ArrowRightIcon className="w-3 h-3" />
              </Link>
            </div>
            {latestNews.length === 0 ? (
              <p className="text-gray-400 text-sm p-5">No hay noticias publicadas aún.</p>
            ) : (
              <ul className="divide-y divide-gray-50">
                {latestNews.map(n => (
                  <li key={n.id}>
                    <Link href="/noticias" className="flex items-start gap-3 px-5 py-4 hover:bg-gray-50 transition-colors">
                      <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0 mt-0.5">
                        <NewspaperIcon className="w-4 h-4 text-blue-500" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-800 truncate">{n.title}</p>
                        <p className="text-xs text-gray-400 mt-0.5">{n.author.name} · {timeAgo(new Date(n.createdAt))}</p>
                      </div>
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </div>

          {/* Panel lateral */}
          <div className="space-y-4">
            {/* Documentos recientes */}
            <div className="bg-white rounded-xl border border-gray-100 shadow-sm">
              <div className="flex items-center justify-between px-5 py-4 border-b border-gray-50">
                <h3 className="font-semibold text-gray-700 text-sm">Documentos recientes</h3>
                <Link href="/documentos" className="flex items-center gap-1 text-xs text-green-600 hover:text-green-800 font-medium">
                  Ver <ArrowRightIcon className="w-3 h-3" />
                </Link>
              </div>
              {recentDocs.length === 0 ? (
                <p className="text-gray-400 text-sm p-5">Sin documentos aún.</p>
              ) : (
                <ul className="divide-y divide-gray-50">
                  {recentDocs.map(d => (
                    <li key={d.id} className="px-5 py-3 flex items-center gap-3">
                      <span className={`px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${TYPE_COLOR[d.type] ?? 'bg-gray-100 text-gray-600'}`}>
                        {d.type.slice(0, 4)}
                      </span>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-medium text-gray-700 truncate">{d.title}</p>
                        <p className="text-xs text-gray-400">v{d.version} · {timeAgo(new Date(d.updatedAt))}</p>
                      </div>
                      <span className={`px-1.5 py-0.5 rounded-full text-xs flex-shrink-0 ${STATUS_COLOR[d.status] ?? ''}`}>
                        {d.status === 'VIGENTE' ? '✓' : d.status === 'BORRADOR' ? '○' : '—'}
                      </span>
                    </li>
                  ))}
                </ul>
              )}
            </div>

            {/* Sugerencias pendientes (solo admins) */}
            {isAdmin && (
              <Link href="/sugerencias" className={`block bg-white rounded-xl border shadow-sm p-5 hover:shadow-md transition-shadow ${
                pendingSuggestions > 0 ? 'border-orange-200' : 'border-gray-100'
              }`}>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className={`rounded-xl p-2.5 ${pendingSuggestions > 0 ? 'bg-orange-100' : 'bg-gray-100'}`}>
                      <ChatBubbleLeftIcon className={`w-5 h-5 ${pendingSuggestions > 0 ? 'text-orange-600' : 'text-gray-400'}`} />
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-gray-700">Sugerencias / TI</p>
                      <p className="text-xs text-gray-400">
                        {pendingSuggestions > 0
                          ? `${pendingSuggestions} pendiente${pendingSuggestions > 1 ? 's' : ''}`
                          : 'Sin pendientes'}
                      </p>
                    </div>
                  </div>
                  {pendingSuggestions > 0 && (
                    <span className="w-6 h-6 bg-orange-500 text-white rounded-full text-xs flex items-center justify-center font-bold">
                      {pendingSuggestions > 9 ? '9+' : pendingSuggestions}
                    </span>
                  )}
                </div>
              </Link>
            )}
          </div>
        </div>

        {/* Accesos rápidos */}
        <div>
          <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Accesos rápidos</h3>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
            {quickLinks.map(({ href, label, icon: Icon, desc }) => (
              <Link
                key={href}
                href={href}
                className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 flex flex-col items-center gap-2 text-center hover:shadow-md hover:border-green-200 transition-all group"
              >
                <div className="w-10 h-10 rounded-xl bg-gray-50 group-hover:bg-green-50 flex items-center justify-center transition-colors">
                  <Icon className="w-5 h-5 text-gray-400 group-hover:text-green-600 transition-colors" />
                </div>
                <div>
                  <p className="text-xs font-semibold text-gray-700">{label}</p>
                  <p className="text-xs text-gray-400 leading-tight mt-0.5 hidden sm:block">{desc}</p>
                </div>
              </Link>
            ))}
          </div>
        </div>

        {/* Footer info */}
        <div className="flex items-center gap-2 text-xs text-gray-300 pt-2">
          <ClockIcon className="w-3.5 h-3.5" />
          <span>Datos actualizados al {new Date().toLocaleTimeString('es-CL', { hour: '2-digit', minute: '2-digit' })}</span>
        </div>

      </div>
    </div>
  )
}
