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

import React, { useEffect, useState } from 'react';
import { Outlet } from 'react-router-dom';
import { 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>>;
    isAdmin: boolean;
    showSettings: boolean;
    setShowSettings: React.Dispatch<React.SetStateAction<boolean>>;
}

export default function Layout({ darkMode, setDarkMode }: LayoutProps) {
    const [isAdmin, setIsAdmin] = useState<boolean>(!!getToken());
    const [navTitle, setNavTitle] = useState<string>('');
    const [navSubtitle, setNavSubtitle] = useState<string>('');
    const [showSettings, setShowSettings] = useState<boolean>(false);

    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,
        isAdmin,
        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}
                    isAdmin={isAdmin}
                    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>
    );
}