import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Navigate, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { logoutUser } from '../auth/authSlice';
import { Button } from '../../common/components/ui/button';
import type { RootState, AppDispatch } from '../../store/store';
import {
    Bell,
    Search
} from 'lucide-react';
import Sidebar from './Sidebar';
import { getDashboardPath } from '../../services/firestoreService';
import { useSessionPersistence } from '../../hooks/useSessionPersistence';

/**
 * Main Application Layout for Authenticated Users.
 * Includes Sidebar, Header, and Content Area.
 * Handles role-based navigation rendering and validates user access to dashboard routes.
 */
const AppLayout: React.FC = () => {
    // Initialize session persistence and token refresh
    useSessionPersistence();

    // Typed selectors
    const { isAuthenticated, user } = useSelector((state: RootState) => state.auth);
    const dispatch = useDispatch<AppDispatch>();
    const location = useLocation();
    const navigate = useNavigate();
    const [sidebarOpen, setSidebarOpen] = React.useState(true);

    // Validate dashboard access based on user role
    useEffect(() => {
        if (!user?.userRole) return;

        const currentPath = location.pathname;
        const correctDashboard = getDashboardPath(user.userRole);

        // If user is trying to access a dashboard route
        if (currentPath.startsWith('/dashboard/')) {
            // Check if the current dashboard doesn't match their role
            if (currentPath !== correctDashboard) {
                // Redirect to their correct dashboard
                navigate(correctDashboard, { replace: true });
            }
        }
    }, [location.pathname, user?.userRole, navigate]);

    // Auth Guard: Redirect to login if not authenticated
    if (!isAuthenticated) {
        return <Navigate to="/login" replace />;
    }

    const handleLogout = () => {
        dispatch(logoutUser()).then(() => {
            // Navigate to login page after logout is complete
            navigate('/login', { replace: true });
        });
    };

    return (
        <div className="flex h-screen bg-slate-50 overflow-hidden">
            <Sidebar
                sidebarOpen={sidebarOpen}
                setSidebarOpen={setSidebarOpen}
                user={user ? { name: user.displayName || undefined, role: user.userRole } : null}
                onLogout={handleLogout}
            />

            {/* Main Content */}
            <main className="flex-1 flex flex-col overflow-hidden relative">
                {/* Top Header */}
                <header className="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-6 z-10 shrink-0">
                    <div className="flex items-center text-sm text-secondary-text">
                        <span className="font-medium text-primary-text">Workspace</span>
                        <span className="mx-2">/</span>
                        <span className="capitalize">{location.pathname.split('/')[1] || 'Dashboard'}</span>
                    </div>

                    <div className="flex items-center space-x-4">
                        <div className="relative hidden md:block">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-text" size={16} />
                            <input
                                type="text"
                                placeholder="Search..."
                                className="h-9 pl-9 pr-4 rounded-full bg-slate-100 border-none text-sm focus:ring-2 focus:ring-primary/20 w-64"
                            />
                        </div>
                        <Button variant="ghost" size="icon" className="relative">
                            <Bell size={20} className="text-secondary-text" />
                            <span className="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full border border-white"></span>
                        </Button>
                    </div>
                </header>

                {/* Content Area */}
                <div className="flex-1 overflow-auto p-6">
                    <div className="max-w-7xl mx-auto">
                        <Outlet />
                    </div>
                </div>
            </main>
        </div>
    );
};

export default AppLayout;