'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  ClipboardList,
  Users,
  BarChart3,
  FileText,
  Dumbbell,
  LogOut,
  Eye,
  X,
} from 'lucide-react';
import { cn } from '@/lib/cn';
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_admin_view_role';

type MenuItem = {
  name: string;
  href: string;
  icon: typeof ClipboardList;
  roles?: string[];
};

const navigation: MenuItem[] = [
  { name: 'Рецепция', href: '/reception', icon: ClipboardList },
  { name: 'Распределение', href: '/distribution', icon: Users, roles: ['SUPER_ADMIN', 'CLUB_ADMIN', 'MANAGER', 'RECEPTIONIST'] },
  { name: 'Аналитика', href: '/analytics', icon: BarChart3, roles: ['SUPER_ADMIN', 'CLUB_ADMIN', 'MANAGER'] },
  { name: 'Отчёты', href: '/reports', icon: FileText, roles: ['SUPER_ADMIN', 'CLUB_ADMIN', 'MANAGER'] },
  { name: 'Тренеры', href: '/trainers', icon: Dumbbell },
];

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 ?? 'RECEPTIONIST';

  const visibleItems = navigation.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 flex flex-col bg-sidebar-bg z-50',
          'transition-transform duration-300',
          'md:relative md:z-auto md:translate-x-0',
          open ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
        )}
      >
        {/* Logo */}
        <div className="flex h-16 items-center justify-between border-b border-sidebar-text/10 px-6">
          <div className="flex items-center gap-2">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sidebar-active">
              <span className="text-sm font-bold text-white">F</span>
            </div>
            <span className="text-lg font-bold text-sidebar-text">
              My<span className="text-primary">Fit</span>CRM
            </span>
          </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>
        )}

        {/* Navigation */}
        <nav className="flex-1 space-y-1 px-3 py-4">
          {visibleItems.map((item) => {
            const isActive = pathname.startsWith(item.href);
            const Icon = item.icon;

            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  'flex items-center gap-3 rounded-xl px-3 py-2.5 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.name}
              </Link>
            );
          })}
        </nav>

        {/* User info + Logout */}
        <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>
    </>
  );
}
