'use client';

import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { ThemeProvider } from '@mui/material/styles';
import { CssBaseline, Box, CircularProgress } from '@mui/material';
import '@fontsource/roboto/300.css';
import '@fontsource/roboto/400.css';
import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css';

import { AdminLayout } from '@/components/admin/layout/admin-layout';
import { adminTheme } from '@/lib/admin-theme';

interface AdminUser {
  id: string;
  email: string;
  name: string | null;
  role: string;
}

export default function AdminLayoutPage({
  children,
}: {
  children: React.ReactNode;
}) {
  const [admin, setAdmin] = useState<AdminUser | null>(null);
  const [loading, setLoading] = useState(true);
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    const checkAuth = async () => {
      // Skip auth check if already on login page
      if (pathname === '/admin/login') {
        setLoading(false);
        return;
      }

      try {
        const response = await fetch('/api/admin/auth/me', {
          credentials: 'include'
        });

        if (response.ok) {
          const data = await response.json();
          setAdmin(data.user);
        } else {
          // 401 is expected when not logged in - don't log as error
          setAdmin(null);
          router.push('/admin/login');
        }
      } catch (error) {
        // Only log actual network errors, not auth failures
        if (error instanceof TypeError) {
          console.error('Network error during auth check:', error);
        }
        setAdmin(null);
        router.push('/admin/login');
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, [pathname, router]);

  if (loading) {
    return (
      <ThemeProvider theme={adminTheme}>
        <CssBaseline />
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            minHeight: '100vh',
          }}
        >
          <CircularProgress />
        </Box>
      </ThemeProvider>
    );
  }

  return (
    <ThemeProvider theme={adminTheme}>
      <CssBaseline />
      {admin && pathname !== '/admin/login' ? (
        <AdminLayout user={admin}>
          {children}
        </AdminLayout>
      ) : (
        children
      )}
    </ThemeProvider>
  );
}