// frontend/src/components/Layout/Layout.tsx

import React, { useEffect, useState } from 'react';
import { Outlet } from 'react-router-dom';
import api, { getToken } from '../../services/api';
import ThemeButton from "../UI/ThemeButton";
import Navbar from './Navbar';

interface LayoutProps {
    darkMode: boolean;
    setDarkMode: (value: boolean) => void;
}

export interface OutletContextType {
    setNavTitle: React.Dispatch<React.SetStateAction<string>>;
    setNavSubtitle: React.Dispatch<React.SetStateAction<string>>;
    role: 'admin' | 'ref' | null;
    showSettings: boolean;
    setShowSettings: React.Dispatch<React.SetStateAction<boolean>>;
}

export default function Layout({ darkMode, setDarkMode }: LayoutProps) {
    const [role, setRole] = useState<'admin' | 'ref' | null>(null);
    const [navTitle, setNavTitle] = useState<string>('');
    const [navSubtitle, setNavSubtitle] = useState<string>('');
    const [showSettings, setShowSettings] = useState<boolean>(false);

    useEffect(() => {
        const verifyAuth = async () => {
            if (getToken()) {
                try {
                    const res = await api.get<{ role: 'admin' | 'ref' }>('/auth/check');
                    setRole(res.role);
                } catch {
                    setRole(null);
                    localStorage.removeItem('volleyToken');
                }
            }
        };
        verifyAuth();
    }, []);

    useEffect(() => {
        if (navTitle) {
            document.title = `${navTitle} | VolleyManager`;
        } else {
            document.title = 'VolleyManager';
        }
    }, [navTitle]);

    const handleLogout = () => {
        localStorage.removeItem('volleyToken');
        window.location.reload();
    };

    const contextValue: OutletContextType = {
        setNavTitle,
        setNavSubtitle,
        role,
        showSettings,
        setShowSettings
    };

    return (
        <div className="fixed inset-0 min-h-screen bg-zinc-50 dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 transition-colors flex flex-col overflow-hidden print:static print:overflow-visible print:h-auto print:bg-white print:text-black">
            <div className="print:hidden shrink-0">
                <Navbar
                    title={navTitle}
                    subtitle={navSubtitle}
                    isAuthenticated={!!role}
                    onLogout={handleLogout}
                />
            </div>

            <main className="flex-1 overflow-hidden relative flex flex-col print:overflow-visible print:h-auto print:block">
                <Outlet context={contextValue} />
            </main>

            <ThemeButton darkMode={darkMode} setDarkMode={setDarkMode} />
        </div>
    );
}