"use client";

import { useState, useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { Bars3Icon } from '@heroicons/react/24/outline';
import Drawer from './Drawer';
import api from '../../../lib/api';
import { UserInfo } from '../../../types';

export default function AppShell({ children }: { children: React.ReactNode }) {
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const pathname = usePathname();
    const router = useRouter();
    const [authorized, setAuthorized] = useState(false);
    const [authChecked, setAuthChecked] = useState(false);
    const [user, setUser] = useState<UserInfo | null>(null);

    useEffect(() => {
        let cancelled = false;
        api.get('/auth/me')
            .then((res) => {
                if (cancelled) return;
                setUser(res.data);
                setAuthorized(true);
            })
            .catch(() => {
                if (cancelled) return;
                setAuthorized(false);
            })
            .finally(() => {
                if (cancelled) return;
                setAuthChecked(true);
            });

        return () => {
            cancelled = true;
        };
    }, []);

    // Pages that must render WITHOUT a session (login + forced MFA enrolment).
    const isPublicAuthPage = pathname === '/login' || pathname.startsWith('/mfa-setup');

    useEffect(() => {
        if (!authChecked) return;
        if (isPublicAuthPage) return;
        if (!authorized) router.push('/login');
    }, [authChecked, authorized, isPublicAuthPage, router]);

    if (isPublicAuthPage) {
        return <>{children}</>;
    }

    if (!authChecked) {
        return null;
    }

    if (!authorized) {
        return null;
    }

    return (
        <div className="min-h-screen bg-white">
            <Drawer sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} user={user} />

            <div className="lg:pl-72">
                <div className="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-gray-200 bg-white px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8 lg:hidden">
                    <button
                        type="button"
                        className="-m-2.5 p-2.5 text-gray-700 lg:hidden"
                        onClick={() => setSidebarOpen(true)}
                    >
                        <span className="sr-only">Open sidebar</span>
                        <Bars3Icon className="h-6 w-6" aria-hidden="true" />
                    </button>
                    <div className="flex flex-1 items-center gap-2">
                        <img src="/logo.svg" alt="VulnCheck Logo" className="h-8 w-8" />
                        <div className="text-sm font-bold leading-6 text-gray-900 font-mono tracking-tighter">Vuln<span className="text-vulncheck-blue">Check</span></div>
                    </div>
                </div>

                <main className="py-10">
                    <div className="px-4 sm:px-6 lg:px-8">{children}</div>
                </main>
            </div>
        </div>
    );
}
