'use client';

import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import {
  FiHome, FiTv, FiFilm, FiMonitor, FiSearch,
  FiHeart, FiUser, FiX, FiSettings, FiCalendar,
  FiChevronLeft, FiChevronRight, FiActivity,
} from 'react-icons/fi';
import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import { cn } from '@/lib/utils';
import { ROUTES } from '@/lib/constants';

const mainLinks = [
  { href: ROUTES.HOME, label: 'Inicio', icon: FiHome },
  { href: ROUTES.TV, label: 'TV en Vivo', icon: FiTv },
  { href: ROUTES.MOVIES, label: 'Películas', icon: FiFilm },
  { href: ROUTES.SERIES, label: 'Series', icon: FiMonitor },
  { href: ROUTES.SEARCH, label: 'Buscar', icon: FiSearch },
  { href: ROUTES.FAVORITES, label: 'Favoritos', icon: FiHeart },
  { href: ROUTES.SPEED_TEST, label: 'Prueba de Red', icon: FiActivity },
  { href: ROUTES.PROFILE, label: 'Mi Perfil', icon: FiUser },
];

export default function Sidebar() {
  const pathname = usePathname();
  const { user } = useAuthStore();
  const { sidebarOpen, setSidebarOpen, sidebarCollapsed, toggleSidebarCollapse } = useUIStore();

  return (
    <>
      {/* Mobile overlay */}
      <AnimatePresence>
        {sidebarOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 lg:hidden"
            onClick={() => setSidebarOpen(false)}
          />
        )}
      </AnimatePresence>

      {/* Sidebar */}
      <aside
        className={cn(
          'fixed top-0 left-0 h-full z-50 lg:z-30 bg-sidebar-gradient border-r border-white/5',
          'transition-all duration-300 ease-out',
          sidebarCollapsed ? 'w-20' : 'w-64',
          'lg:translate-x-0 lg:top-16',
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        )}
      >
        {/* Mobile close */}
        <div className="flex items-center justify-between p-4 lg:hidden border-b border-white/5">
          <div className="flex items-center gap-2">
            <img
              src="/logo.png"
              alt="Cat Tv"
              className="h-11 w-auto object-contain select-none"
            />
          </div>
          <button
            onClick={() => setSidebarOpen(false)}
            className="p-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all"
          >
            <FiX size={20} />
          </button>
        </div>

        {/* Desktop Collapse Button */}
        <div className="hidden lg:flex justify-end p-2 border-b border-white/5">
          <button
            onClick={toggleSidebarCollapse}
            className="p-1.5 rounded-lg text-white/40 hover:text-white hover:bg-white/5 transition-all duration-200"
            title={sidebarCollapsed ? "Expandir menú" : "Colapsar menú"}
          >
            {sidebarCollapsed ? <FiChevronRight size={18} /> : <FiChevronLeft size={18} />}
          </button>
        </div>

        <nav className="p-3 space-y-1 mt-2">
          {!sidebarCollapsed && (
            <p className="px-4 py-2 text-xs font-semibold text-white/30 uppercase tracking-wider">
              Menú Principal
            </p>
          )}
          {mainLinks.map((link) => {
            const isActive = pathname === link.href || pathname?.startsWith(link.href + '/');
            const Icon = link.icon;
            return (
              <Link
                key={link.href}
                href={link.href}
                onClick={() => setSidebarOpen(false)}
                className={cn(
                  'flex items-center rounded-lg transition-all duration-300',
                  sidebarCollapsed ? 'justify-center p-3' : 'gap-3 px-4 py-3',
                  isActive
                    ? 'text-white bg-primary/10 border-l-2 border-primary shadow-sm shadow-primary/10'
                    : 'text-white/50 hover:text-white hover:bg-white/5'
                )}
                title={sidebarCollapsed ? link.label : undefined}
              >
                <Icon size={20} className={cn(isActive && 'text-primary')} />
                {!sidebarCollapsed && <span className="font-medium text-sm">{link.label}</span>}
                {!sidebarCollapsed && link.href === ROUTES.TV && (
                  <span className="ml-auto w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                )}
              </Link>
            );
          })}

          {/* Admin section */}
          {user?.role === 'admin' && (
            <>
              <div className="my-4 border-t border-white/5" />
              {!sidebarCollapsed && (
                <p className="px-4 py-2 text-xs font-semibold text-white/30 uppercase tracking-wider">
                  Administración
                </p>
              )}
              <Link
                href={ROUTES.ADMIN}
                onClick={() => setSidebarOpen(false)}
                className={cn(
                  'flex items-center rounded-lg transition-all duration-300',
                  sidebarCollapsed ? 'justify-center p-3' : 'gap-3 px-4 py-3',
                  pathname?.startsWith('/admin')
                    ? 'text-white bg-accent/10 border-l-2 border-accent'
                    : 'text-white/50 hover:text-white hover:bg-white/5'
                )}
                title={sidebarCollapsed ? "Panel Admin" : undefined}
              >
                <FiSettings size={20} className={cn(pathname?.startsWith('/admin') && 'text-accent')} />
                {!sidebarCollapsed && <span className="font-medium text-sm">Panel Admin</span>}
              </Link>
            </>
          )}
        </nav>

        {/* Bottom user card */}
        <div className="absolute bottom-0 left-0 right-0 p-4 border-t border-white/5">
          <div className="flex items-center gap-3 justify-center">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-accent flex items-center justify-center font-bold text-sm flex-shrink-0 text-white">
              {user?.username?.charAt(0)?.toUpperCase() || 'U'}
            </div>
            {!sidebarCollapsed && (
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-white truncate">{user?.username || 'Usuario'}</p>
                <p className="text-xs text-white/40 truncate">{user?.email || ''}</p>
              </div>
            )}
          </div>
        </div>
      </aside>
    </>
  );
}
