'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { motion, AnimatePresence } from 'framer-motion'
import {
  LayoutDashboard, FileText, Kanban, Building2, Users,
  ChevronLeft, ChevronRight, Settings, Moon, Sun, LogOut,
} from 'lucide-react'
import { cn, generateInitials } from '@/lib/utils'
import { useTheme } from './ThemeProvider'
import { useAppStore } from '@/store/useAppStore'
import { useAuthStore } from '@/store/authStore'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { useRouter } from 'next/navigation'

const NAV_ITEMS = [
  { href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/operaciones', label: 'Operaciones', icon: FileText },
  { href: '/kanban', label: 'Tablero Kanban', icon: Kanban },
  { href: '/propiedades', label: 'Propiedades', icon: Building2 },
  { href: '/clientes', label: 'Clientes', icon: Users },
]

export function Sidebar() {
  const pathname = usePathname()
  const { resolvedTheme, setTheme } = useTheme()
  const { sidebarOpen, setSidebarOpen } = useAppStore()
  const { user, logout } = useAuthStore()
  const router = useRouter()

  const handleLogout = () => {
    logout()
    router.push('/login')
  }

  return (
    <motion.aside
      animate={{ width: sidebarOpen ? 240 : 64 }}
      transition={{ duration: 0.2, ease: 'easeInOut' }}
      className="relative flex flex-col h-screen bg-sidebar text-sidebar-foreground border-r border-sidebar-border overflow-hidden flex-shrink-0"
    >
      {/* Logo / Branding */}
      <div className="flex items-center h-auto py-4 px-4 border-b border-sidebar-border gap-3">
        {/* Escudo / Logo */}
        <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-blue-600 flex items-center justify-center text-white font-bold text-sm select-none">
          HA
        </div>
        <AnimatePresence>
          {sidebarOpen && (
            <motion.div
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -10 }}
              className="flex flex-col min-w-0"
            >
              <span className="font-bold text-sm text-white leading-tight whitespace-nowrap">Horacio E. Acosta</span>
              <span className="text-xs text-sidebar-foreground/60 whitespace-nowrap">Negocios Inmobiliarios</span>
            </motion.div>
          )}
        </AnimatePresence>
        <button
          onClick={() => setSidebarOpen(!sidebarOpen)}
          className="ml-auto p-1.5 rounded-md hover:bg-sidebar-accent transition-colors text-sidebar-foreground flex-shrink-0"
        >
          {sidebarOpen ? <ChevronLeft size={16} /> : <ChevronRight size={16} />}
        </button>
      </div>

      {/* Nav */}
      <nav className="flex-1 py-4 px-2 space-y-1 overflow-y-auto">
        {NAV_ITEMS.map(({ href, label, icon: Icon }) => {
          const active = pathname.startsWith(href)
          return (
            <Link key={href} href={href}>
              <motion.div
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                className={cn(
                  'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors cursor-pointer',
                  active
                    ? 'bg-blue-600 text-white'
                    : 'hover:bg-sidebar-accent text-sidebar-foreground'
                )}
              >
                <Icon size={18} className="flex-shrink-0" />
                <AnimatePresence>
                  {sidebarOpen && (
                    <motion.span
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: -10 }}
                      className="text-sm font-medium whitespace-nowrap"
                    >
                      {label}
                    </motion.span>
                  )}
                </AnimatePresence>
              </motion.div>
            </Link>
          )
        })}
      </nav>

      {/* Footer */}
      <div className="p-2 border-t border-sidebar-border space-y-1">
        <button
          onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
          className="flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-sidebar-accent w-full transition-colors text-sidebar-foreground"
        >
          {resolvedTheme === 'dark' ? <Sun size={18} /> : <Moon size={18} />}
          {sidebarOpen && (
            <span className="text-sm">{resolvedTheme === 'dark' ? 'Modo claro' : 'Modo oscuro'}</span>
          )}
        </button>

        <Link href="/configuracion">
          <div className="flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-sidebar-accent transition-colors cursor-pointer">
            <Settings size={18} />
            {sidebarOpen && <span className="text-sm">Configuración</span>}
          </div>
        </Link>

        {user && (
          <div className="flex items-center gap-3 px-3 py-2.5 rounded-lg mt-1 group">
            <Avatar className="h-7 w-7 flex-shrink-0">
              <AvatarFallback className="bg-blue-600 text-white text-xs">
                {generateInitials(user.name)}
              </AvatarFallback>
            </Avatar>
            {sidebarOpen && (
              <>
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-medium truncate text-sidebar-foreground">{user.name}</p>
                  <p className="text-xs text-sidebar-foreground/50 truncate">{user.role}</p>
                </div>
                <button
                  onClick={handleLogout}
                  title="Cerrar sesión"
                  className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-sidebar-accent transition-all text-sidebar-foreground/50 hover:text-red-400"
                >
                  <LogOut size={14} />
                </button>
              </>
            )}
          </div>
        )}

        {/* Branding footer */}
        {sidebarOpen && (
          <div className="px-3 pt-2 pb-1">
            <p className="text-xs text-sidebar-foreground/30 text-center">horacioeacosta.com</p>
          </div>
        )}
      </div>
    </motion.aside>
  )
}
