'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  LayoutDashboard,
  Building2,
  KeyRound,
  Activity,
  ScrollText,
  GitBranch,
  FileText,
  Palette,
  Briefcase,
  CalendarCheck,
  LogOut,
  Eye,
  X,
} from 'lucide-react';
import { cn } from '@/lib/cn';
import { Logo } from '@/components/ui/logo';
import { logout } from '@/lib/auth';
import { api } from '@/lib/api';

type UserProfile = {
  id: string;
  firstName: string;
  lastName: string;
  role: string;
  phone: string;
};

const ROLE_LABELS: Record<string, string> = {
  SUPER_ADMIN: 'Суперадминистратор',
  CLUB_ADMIN: 'Админ клуба',
  MANAGER: 'Фитнес-менеджер',
  COORDINATOR: 'Координатор',
  TRAINER: 'Тренер',
  RECEPTIONIST: 'Рецепция',
};

const VIEW_ROLE_KEY = 'fitcrm_view_role';

type MenuItem = {
  href: string;
  label: string;
  icon: typeof LayoutDashboard;
  roles?: string[];
};

const menuItems: MenuItem[] = [
  { href: '/dashboard', label: 'Дашборд', icon: LayoutDashboard },
  { href: '/clubs', label: 'Клубы', icon: Building2, roles: ['SUPER_ADMIN'] },
  {
    href: '/crm',
    label: 'CRM',
    icon: Briefcase,
    roles: ['SUPER_ADMIN', 'CLUB_ADMIN', 'MANAGER', 'COORDINATOR'],
  },
  {
    href: '/bookings',
    label: 'Записи',
    icon: CalendarCheck,
    roles: ['SUPER_ADMIN', 'CLUB_ADMIN', 'MANAGER', 'COORDINATOR', 'TRAINER'],
  },
  { href: '/licenses', label: 'Лицензии', icon: KeyRound, roles: ['SUPER_ADMIN'] },
  { href: '/monitoring', label: 'Мониторинг', icon: Activity, roles: ['SUPER_ADMIN'] },
  {
    href: '/audit',
    label: 'Журнал действий',
    icon: ScrollText,
    roles: ['SUPER_ADMIN', 'CLUB_ADMIN'],
  },
  { href: '/documents', label: 'Документы', icon: FileText, roles: ['SUPER_ADMIN'] },
  { href: '/development', label: 'Разработка', icon: GitBranch, roles: ['SUPER_ADMIN'] },
  {
    href: '/settings/themes',
    label: 'Темы оформления',
    icon: Palette,
    roles: ['SUPER_ADMIN', 'CLUB_ADMIN'],
  },
];

interface SidebarProps {
  open?: boolean;
  onClose?: () => void;
}

export function Sidebar({ open, onClose }: SidebarProps) {
  const pathname = usePathname();
  const [user, setUser] = useState<UserProfile | null>(null);
  const [viewRole, setViewRole] = useState<string | null>(null);

  const syncViewRole = useCallback(() => {
    setViewRole(typeof window !== 'undefined' ? localStorage.getItem(VIEW_ROLE_KEY) : null);
  }, []);

  useEffect(() => {
    onClose?.();
  }, [pathname, onClose]);

  useEffect(() => {
    api
      .get<UserProfile>('/auth/profile')
      .then(setUser)
      .catch(() => {});
    syncViewRole();
    window.addEventListener('viewrole-change', syncViewRole);
    return () => window.removeEventListener('viewrole-change', syncViewRole);
  }, [syncViewRole]);

  const effectiveRole = viewRole ?? user?.role ?? 'SUPER_ADMIN';

  const visibleItems = menuItems.filter(
    (item) => !item.roles || item.roles.includes(effectiveRole),
  );

  return (
    <>
      <div
        className={cn(
          'fixed inset-0 z-40 bg-black/50 transition-opacity md:hidden',
          open ? 'opacity-100' : 'opacity-0 pointer-events-none',
        )}
        onClick={onClose}
      />

      <aside
        className={cn(
          'fixed left-0 top-0 h-screen w-64 bg-sidebar-bg flex flex-col z-50',
          'transition-transform duration-300',
          open ? 'translate-x-0' : '-translate-x-full md:translate-x-0',
        )}
      >
        <div className="px-6 py-6 border-b border-sidebar-text/10 flex items-center justify-between">
          <div>
            <Logo size="md" className="text-sidebar-text" />
            <p className="text-sm text-sidebar-text mt-1">
              {ROLE_LABELS[effectiveRole] ?? 'Платформа'}
            </p>
          </div>
          <button
            onClick={onClose}
            className="md:hidden rounded-lg p-1 text-sidebar-text hover:bg-sidebar-active/10"
            aria-label="Закрыть меню"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {viewRole && (
          <div className="mx-3 mt-3 flex items-center gap-2 rounded-lg bg-amber-500/10 px-3 py-2">
            <Eye className="h-3.5 w-3.5 text-amber-400 shrink-0" />
            <span className="text-xs text-amber-300 flex-1 truncate">
              Просмотр: {ROLE_LABELS[viewRole]}
            </span>
          </div>
        )}

        <nav className="flex-1 overflow-y-auto py-4 px-3">
          <ul className="space-y-1">
            {visibleItems.map((item) => {
              const isActive = pathname === item.href || pathname.startsWith(item.href + '/');
              const Icon = item.icon;
              return (
                <li key={item.href}>
                  <Link
                    href={item.href}
                    className={cn(
                      'flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors',
                      isActive
                        ? 'bg-sidebar-active text-white'
                        : 'text-sidebar-text hover:bg-sidebar-active/10 hover:text-sidebar-text',
                    )}
                  >
                    <Icon className="h-5 w-5 shrink-0" />
                    {item.label}
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        <div className="border-t border-sidebar-text/10 p-4">
          <div className="flex items-center gap-3">
            <Link
              href="/profile"
              className="flex items-center gap-3 flex-1 min-w-0 rounded-lg transition-colors hover:bg-sidebar-active/10 -m-1 p-1"
            >
              <div className="flex h-9 w-9 items-center justify-center rounded-full bg-sidebar-active/20 shrink-0">
                <span className="text-sm font-medium text-sidebar-text">
                  {user ? `${user.firstName[0]}${user.lastName[0]}` : 'СА'}
                </span>
              </div>
              <div className="flex-1 overflow-hidden">
                <p className="truncate text-sm font-medium text-sidebar-text">
                  {user ? `${user.firstName} ${user.lastName}` : 'Загрузка...'}
                </p>
                <p className="truncate text-xs text-sidebar-text/60">
                  {user ? (ROLE_LABELS[user.role] ?? user.role) : ''}
                </p>
              </div>
            </Link>
            <button
              onClick={logout}
              className="rounded-lg p-1.5 text-sidebar-text/60 transition-colors hover:bg-sidebar-active/10 hover:text-sidebar-text shrink-0"
              title="Выйти"
            >
              <LogOut className="h-4 w-4" />
            </button>
          </div>
        </div>
      </aside>
    </>
  );
}
