import { useState } from 'react';
import {
  Avatar, Button, Card, CardContent, ScrollShadow, Tooltip,
  Select, SelectTrigger, SelectValue, SelectPopover, ListBox, ListBoxItem
} from '@heroui/react';
import {
  LogOut, PanelLeftClose, PanelLeft, Activity, AudioLines, CalendarDays,
  ClipboardList, Home, LogIn, Music, Puzzle, RadioTower, Settings,
  Shield, Sparkles, Tag, Ticket, Wrench
} from 'lucide-react';
import { useApp } from '../../context/AppContext';

const navGroups = [
  {
    label: 'Dashboard',
    items: [
      { key: 'overview', label: 'Uebersicht', icon: <Home size={18} /> },
    ]
  },
  {
    label: 'Community',
    items: [
      { key: 'welcome', label: 'Willkommen', icon: <Sparkles size={18} /> },
      { key: 'birthday', label: 'Birthday', icon: <CalendarDays size={18} /> },
      { key: 'events', label: 'Events', icon: <Activity size={18} /> },
    ]
  },
  {
    label: 'Support',
    items: [
      { key: 'tickets', label: 'Ticketsystem', icon: <Ticket size={18} /> },
      { key: 'supportlogin', label: 'Support Login', icon: <LogIn size={18} /> },
      { key: 'register', label: 'Registrierung', icon: <ClipboardList size={18} /> },
    ]
  },
  {
    label: 'Moderation',
    items: [
      { key: 'automod', label: 'Automod', icon: <Shield size={18} /> },
      { key: 'reactionroles', label: 'Reaction Roles', icon: <Tag size={18} /> },
    ]
  },
  {
    label: 'Funktionen',
    items: [
      { key: 'dynamicvoice', label: 'Dynamic Voice', icon: <AudioLines size={18} /> },
      { key: 'music', label: 'Musik', icon: <Music size={18} /> },
      { key: 'statuspage', label: 'Statuspage', icon: <RadioTower size={18} /> },
      { key: 'serverstats', label: 'Server Stats', icon: <Activity size={18} /> },
    ]
  },
  {
    label: 'System',
    items: [
      { key: 'modules', label: 'Module', icon: <Puzzle size={18} /> },
      { key: 'settings', label: 'Einstellungen', icon: <Settings size={18} /> },
    ]
  }
];

export function Sidebar() {
  const { user, guilds, currentGuildId, section, setCurrentGuildId, setSection, handleLogout } = useApp();
  const [collapsed, setCollapsed] = useState(false);

  return (
    <aside className={`flex h-full flex-col transition-all duration-200 ${collapsed ? 'w-20' : 'w-72'}`}>
      <div className={`flex items-center gap-3 px-4 pt-4 pb-3 ${collapsed ? 'justify-center' : ''}`}>
        <Avatar name="Papo" radius="lg" />
        {!collapsed && (
          <div className="min-w-0">
            <div className="text-base font-bold">Papo</div>
            <div className="text-[10px] uppercase tracking-widest text-default-400">Dashboard</div>
          </div>
        )}
      </div>

      <div className="px-3 pb-2">
        <Select
          aria-label="Guild auswaehlen"
          selectedKey={currentGuildId}
          onSelectionChange={(key) => {
            if (typeof key === 'string') setCurrentGuildId(key);
          }}
        >
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectPopover>
            <ListBox>
              {guilds.map((g) => (
                <ListBoxItem key={g.id} id={g.id} textValue={g.name}>
                  {collapsed ? g.name.slice(0, 2) : g.name}
                </ListBoxItem>
              ))}
            </ListBox>
          </SelectPopover>
        </Select>
      </div>

      <ScrollShadow className="flex-1 px-2 py-2" hideScrollBar>
        <nav className="flex flex-col gap-4">
          {navGroups.map((group) => (
            <div key={group.label}>
              {!collapsed && (
                <div className="px-2 pb-1 text-[10px] font-semibold uppercase tracking-widest text-default-400">
                  {group.label}
                </div>
              )}
              <div className="flex flex-col gap-0.5">
                {group.items
                  .filter((item) => item.key !== 'admin' || user?.isAdmin)
                  .map((item) => {
                    const isActive = section === item.key;
                    return (
                      <Tooltip key={item.key} content={collapsed ? item.label : ''} placement="right" offset={8}>
                        <Button
                          className="h-9 justify-start gap-3 px-2"
                          color={isActive ? 'primary' : 'default'}
                          radius="lg"
                          variant={isActive ? 'flat' : 'light'}
                          size="sm"
                          startContent={item.icon}
                          onPress={() => setSection(item.key)}
                        >
                          {!collapsed && item.label}
                        </Button>
                      </Tooltip>
                    );
                  })}
              </div>
            </div>
          ))}
          {user?.isAdmin && (
            <div>
              {!collapsed && (
                <div className="px-2 pb-1 text-[10px] font-semibold uppercase tracking-widest text-default-400">
                  Admin
                </div>
              )}
              <Tooltip content={collapsed ? 'Admin' : ''} placement="right" offset={8}>
                <Button
                  className="h-9 justify-start gap-3 px-2"
                  color={section === 'admin' ? 'warning' : 'default'}
                  radius="lg"
                  variant={section === 'admin' ? 'flat' : 'light'}
                  size="sm"
                  startContent={<Wrench size={18} />}
                  onPress={() => setSection('admin')}
                >
                  {!collapsed && 'Admin'}
                </Button>
              </Tooltip>
            </div>
          )}
        </nav>
      </ScrollShadow>

      <div className="p-3 flex flex-col gap-2">
        <Button
          isIconOnly
          className="w-full"
          radius="lg"
          size="sm"
          variant="light"
          onPress={() => setCollapsed((c) => !c)}
        >
          {collapsed ? <PanelLeft size={16} /> : <PanelLeftClose size={16} />}
        </Button>

        <Card>
          <CardContent className={`flex items-center gap-3 p-2 ${collapsed ? 'justify-center' : ''}`}>
            <Avatar name={user?.username} size="sm" className="shrink-0" />
            {!collapsed && (
              <>
                <div className="flex-1 min-w-0">
                  <div className="truncate text-xs font-semibold">{user?.username}</div>
                  <div className="text-[10px] text-default-400">Angemeldet</div>
                </div>
                <Tooltip content="Abmelden" placement="top">
                  <Button isIconOnly color="danger" radius="lg" size="sm" variant="light" onPress={handleLogout}>
                    <LogOut size={14} />
                  </Button>
                </Tooltip>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </aside>
  );
}
