import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from '@/components/ui/sidebar'
import { useAuth } from '@/hooks/use-auth'
import { Home, Settings, Volume2 } from 'lucide-react'
import { Link, useLocation } from 'react-router'
import { NavPlan } from './NavPlan'
import { NavUser } from './NavUser'

const navigationItems = [
  {
    title: 'Dashboard',
    href: '/dashboard',
    icon: Home,
  },
  {
    title: 'Soundboard',
    href: '/soundboard',
    icon: Volume2,
  },
]

const adminNavigationItems = [
  {
    title: 'Sounds',
    href: '/admin/sounds',
    icon: Settings,
  },
]

export function AppSidebar() {
  const { user, logout } = useAuth()
  const { state } = useSidebar()
  const location = useLocation()

  const isOpen = state === 'expanded'

  const handleLogout = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('Logout failed:', error)
    }
  }

  if (!user) return null

  const allNavItems = [
    ...navigationItems,
    ...(user.role === 'admin' ? adminNavigationItems : []),
  ]

  return (
    <Sidebar>
      <SidebarHeader>
        <div className="flex items-center space-x-2">
          <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
            <span className="text-primary-foreground font-bold text-sm">
              SB
            </span>
          </div>
          {isOpen && (
            <div>
              <h2 className="text-lg font-semibold">Soundboard</h2>
              <p className="text-xs text-muted-foreground">v2.0</p>
            </div>
          )}
        </div>
      </SidebarHeader>

      <SidebarContent>
        <SidebarMenu>
          {allNavItems.map(item => {
            const Icon = item.icon
            const isActive = location.pathname === item.href

            return (
              <SidebarMenuItem key={item.href}>
                <SidebarMenuButton asChild isActive={isActive}>
                  <Link to={item.href}>
                    <Icon className="h-4 w-4" />
                    <span>{item.title}</span>
                  </Link>
                </SidebarMenuButton>
              </SidebarMenuItem>
            )
          })}
        </SidebarMenu>
      </SidebarContent>

      <SidebarFooter>
        <NavPlan user={user} />
        <NavUser user={user} logout={handleLogout} />
      </SidebarFooter>
    </Sidebar>
  )
}
