'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/components/id/auth-provider';
import { AdminBadge } from '@/components/id/admin-badge';
import { AdminNav } from '@/components/id/admin-nav';
import { IdShell } from '@/components/id/shell';

export function AdminShell({ active, children }: { active: string; children: React.ReactNode }) {
  const router = useRouter();
  const { user, isLoading } = useAuth();

  useEffect(() => {
    if (!isLoading && user && !user.canAccessAdmin) {
      router.replace('/');
    }
  }, [isLoading, router, user]);

  if (isLoading || !user) {
    return (
      <IdShell active={active} wide>
        <div className="py-20 text-center text-[#667085]">Загрузка админ-панели...</div>
      </IdShell>
    );
  }

  if (!user.canAccessAdmin) {
    return null;
  }

  return (
    <IdShell active="/admin/users" wide>
      <div className="mb-6 flex flex-wrap items-start justify-between gap-4">
        <div>
          <div className="mb-2 flex items-center gap-2">
            <AdminBadge user={user} />
          </div>
          <h1 className="text-4xl font-medium tracking-tight">Админ-панель</h1>
          <p className="mt-2 text-[#667085]">Управление пользователями, OAuth-приложениями и правами доступа</p>
        </div>
      </div>
      <AdminNav active={active} user={user} />
      {children}
    </IdShell>
  );
}
