import { Link, useNavigate } from 'react-router-dom'
import { useAuth } from '../../context/AuthContext'
import { useTheme } from '../../context/ThemeContext'
import { useSettings } from '../../context/SettingsContext'
import { Close, Home, Grid, Live, Fire, User, Logout, Cog, Sun, Moon } from '../icons'

/** Slide-in navigation drawer. */
export default function SideMenu({ open, onClose }) {
  const { user, isAuthenticated, isAdmin, logout } = useAuth()
  const { theme, toggle } = useTheme()
  const { settings } = useSettings()
  const navigate = useNavigate()

  const go = (to) => {
    onClose()
    navigate(to)
  }

  const Item = ({ icon: Icon, label, onClick, danger = false }) => (
    <button
      onClick={onClick}
      className={`flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left text-[14px] font-semibold transition-all duration-150 ${
        danger
          ? 'text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-900/20'
          : 'text-gray-700 hover:bg-gray-100 hover:pl-4 dark:text-gray-200 dark:hover:bg-gray-800'
      }`}
    >
      <Icon
        width={18}
        height={18}
        className={danger ? 'text-rose-400' : 'text-gray-400 dark:text-gray-500'}
      />
      {label}
    </button>
  )

  const Label = ({ children }) => (
    <p className="px-3 pb-1 pt-4 text-[10px] font-bold uppercase tracking-widest text-gray-400 first:pt-1">
      {children}
    </p>
  )

  return (
    <>
      <div
        className={`fixed inset-0 z-50 bg-black/50 backdrop-blur-sm transition-opacity duration-300 ${
          open ? 'opacity-100' : 'pointer-events-none opacity-0'
        }`}
        onClick={onClose}
      />
      <aside
        className={`fixed right-0 top-0 z-50 flex h-full w-72 max-w-[85vw] flex-col bg-white shadow-2xl transition-transform duration-300 ease-out dark:bg-gray-900 ${
          open ? 'translate-x-0' : 'translate-x-full'
        }`}
      >
        <div className="flex items-center justify-between border-b border-gray-100 p-4 dark:border-gray-800">
          <span className="text-lg font-extrabold tracking-tight">
            {settings?.site?.name || 'Menu'}
          </span>
          <button
            onClick={onClose}
            className="rounded-full p-2 text-gray-500 transition hover:bg-gray-100 dark:hover:bg-gray-800"
          >
            <Close />
          </button>
        </div>

        {isAuthenticated && (
          <Link
            to="/profile"
            onClick={onClose}
            className="flex items-center gap-3 border-b border-gray-100 bg-gray-50/60 p-4 transition hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-800/40 dark:hover:bg-gray-800"
          >
            <div className="bg-brand-gradient flex h-11 w-11 items-center justify-center overflow-hidden rounded-full font-bold text-white shadow-md shadow-[var(--brand)]/25">
              {user.avatar ? (
                <img src={user.avatar} alt="" className="h-full w-full object-cover" />
              ) : (
                user.name?.[0]?.toUpperCase()
              )}
            </div>
            <div className="min-w-0">
              <p className="truncate font-bold">{user.name}</p>
              <p className="truncate text-xs text-gray-500">{user.email}</p>
            </div>
          </Link>
        )}

        <nav className="flex-1 space-y-0.5 overflow-y-auto p-3">
          <Label>Browse</Label>
          <Item icon={Home} label="Home" onClick={() => go('/')} />
          <Item icon={Grid} label="Categories" onClick={() => go('/categories')} />
          <Item icon={Live} label="Live" onClick={() => go('/live')} />
          <Item icon={Fire} label="Trending" onClick={() => go('/trending')} />

          <Label>Account</Label>
          {isAuthenticated ? (
            <>
              <Item icon={User} label="Profile" onClick={() => go('/profile')} />
              {isAdmin && <Item icon={Cog} label="Admin Panel" onClick={() => go('/admin')} />}
              <Item
                icon={Logout}
                label="Logout"
                danger
                onClick={async () => {
                  await logout()
                  go('/')
                }}
              />
            </>
          ) : (
            <>
              <Item icon={User} label="Login" onClick={() => go('/login')} />
              <Item icon={User} label="Register" onClick={() => go('/register')} />
            </>
          )}

          <Label>Preferences</Label>
          <Item
            icon={theme === 'dark' ? Sun : Moon}
            label={theme === 'dark' ? 'Light mode' : 'Dark mode'}
            onClick={toggle}
          />
        </nav>

        {!isAuthenticated && (
          <div className="border-t border-gray-100 p-4 dark:border-gray-800">
            <button
              onClick={() => go('/register')}
              className="bg-brand-gradient w-full rounded-xl py-2.5 text-sm font-bold text-white shadow-md shadow-[var(--brand)]/25 transition hover:opacity-90"
            >
              Create free account
            </button>
          </div>
        )}
      </aside>
    </>
  )
}
