'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Loader2, ShieldAlert, ShieldCheck } from 'lucide-react';
import { useAuth } from '@/contexts/auth-context';
import { cn } from '@/lib/utils';

const navigation = [
  { name: 'Курсы', href: '/admin' },
  { name: 'Тикеты поддержки', href: '/admin/support' },
];

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const { loading, backendUser } = useAuth();
  const isStaff = backendUser?.role === 'ADMIN' || backendUser?.role === 'MODERATOR';

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!isStaff) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6">
        <div className="w-full max-w-md rounded-xl border bg-card p-6 text-center">
          <ShieldAlert className="mx-auto mb-3 h-8 w-8 text-rose-500" />
          <p className="text-base font-semibold">Нет доступа к Админ Панели</p>
          <p className="mt-1 text-sm text-muted-foreground">Требуется роль администратора или модератора.</p>
          <Link href="/dashboard" className="mt-4 inline-block text-sm text-primary hover:underline">
            Вернуться в личный кабинет
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/20">
      <header className="border-b bg-background">
        <div className="container flex h-16 items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
              <ShieldCheck className="h-5 w-5 text-primary" />
            </div>
            <div>
              <p className="text-sm font-semibold">Админ Панель</p>
              <p className="text-xs text-muted-foreground">Модерация и поддержка</p>
            </div>
          </div>

          <div className="flex items-center gap-5">
            {navigation.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  'text-sm font-medium',
                  pathname === item.href ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'
                )}
              >
                {item.name}
              </Link>
            ))}
            <Link href="/dashboard" className="text-sm text-primary hover:underline">
              Личный кабинет
            </Link>
          </div>
        </div>
      </header>
      <main className="container py-6">{children}</main>
    </div>
  );
}
