'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useSession } from 'next-auth/react'
import {
  HomeIcon,
  NewspaperIcon,
  UsersIcon,
  ChartBarIcon,
  CalendarIcon,
  ChatBubbleLeftIcon,
  FolderIcon,
  MapIcon,
  UserGroupIcon,
  CurrencyDollarIcon,
  ScaleIcon,
  ShieldCheckIcon,
  Cog6ToothIcon,
  BuildingOffice2Icon,
  GlobeAltIcon,
  SunIcon,
} from '@heroicons/react/24/outline'

const navCorporativo = [
  { href: '/dashboard', label: 'Inicio', icon: HomeIcon },
  { href: '/noticias', label: 'Noticias', icon: NewspaperIcon },
  { href: '/directorio', label: 'Directorio', icon: UsersIcon },
  { href: '/organigrama', label: 'Organigrama', icon: ChartBarIcon },
  { href: '/documentos', label: 'Documentos', icon: FolderIcon },
  { href: '/mapa-procesos', label: 'Mapa de Procesos', icon: MapIcon },
  { href: '/calendario', label: 'Calendario', icon: CalendarIcon },
  { href: '/sugerencias', label: 'Sugerencias / TI', icon: ChatBubbleLeftIcon },
]

const navTransversal = [
  { href: '/rrhh', label: 'RRHH', icon: UserGroupIcon },
  { href: '/finanzas', label: 'Finanzas', icon: CurrencyDollarIcon },
  { href: '/legal', label: 'Legal y Compliance', icon: ScaleIcon },
  { href: '/seguridad', label: 'Seguridad y Prevención', icon: ShieldCheckIcon },
]

const navLineas = [
  { href: '/agricola', label: 'Agrícola', icon: SunIcon, slug: 'agricola' },
  { href: '/inmobiliaria', label: 'Inmobiliaria', icon: BuildingOffice2Icon, slug: 'inmobiliaria' },
  { href: '/forestal', label: 'Forestal', icon: GlobeAltIcon, slug: 'forestal' },
]

function NavItem({ href, label, icon: Icon }: { href: string; label: string; icon: React.ElementType }) {
  const pathname = usePathname()
  const active = pathname === href || pathname.startsWith(href + '/')
  return (
    <Link
      href={href}
      className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${
        active
          ? 'bg-green-700 text-white font-medium'
          : 'text-gray-300 hover:bg-gray-700 hover:text-white'
      }`}
    >
      <Icon className="w-5 h-5 flex-shrink-0" />
      {label}
    </Link>
  )
}

export default function Sidebar() {
  const { data: session } = useSession()
  const role = (session?.user as any)?.role
  const businessLines: string[] = (session?.user as any)?.businessLines ?? []
  const isAdmin = role === 'SUPER_ADMIN' || role === 'ADMIN'

  const lineasVisibles =
    isAdmin || role === 'GERENCIAL'
      ? navLineas
      : navLineas.filter((l) => businessLines.includes(l.slug))

  return (
    <aside className="w-64 min-h-screen bg-gray-800 flex flex-col">
      <div className="p-4 border-b border-gray-700">
        <h1 className="text-white font-bold text-lg">AILLIN</h1>
        <p className="text-gray-400 text-xs">Intranet Corporativa</p>
      </div>

      <nav className="flex-1 p-3 space-y-6 overflow-y-auto">
        <div>
          <p className="text-gray-500 text-xs uppercase tracking-wider px-3 mb-2">Corporativo</p>
          <div className="space-y-1">
            {navCorporativo.map((item) => (
              <NavItem key={item.href} {...item} />
            ))}
          </div>
        </div>

        <div>
          <p className="text-gray-500 text-xs uppercase tracking-wider px-3 mb-2">Transversal</p>
          <div className="space-y-1">
            {navTransversal.map((item) => (
              <NavItem key={item.href} {...item} />
            ))}
          </div>
        </div>

        {lineasVisibles.length > 0 && (
          <div>
            <p className="text-gray-500 text-xs uppercase tracking-wider px-3 mb-2">Líneas de Negocio</p>
            <div className="space-y-1">
              {lineasVisibles.map((item) => (
                <NavItem key={item.href} {...item} />
              ))}
            </div>
          </div>
        )}

        {isAdmin && (
          <div>
            <p className="text-gray-500 text-xs uppercase tracking-wider px-3 mb-2">Administración</p>
            <NavItem href="/admin" label="Administración" icon={Cog6ToothIcon} />
          </div>
        )}
      </nav>

      <div className="p-4 border-t border-gray-700">
        <p className="text-gray-400 text-xs truncate">{session?.user?.name}</p>
        <p className="text-gray-500 text-xs truncate">{session?.user?.email}</p>
      </div>
    </aside>
  )
}
