import React, { type ReactNode, useState, useEffect } from 'react';
import { Box, AppBar, Toolbar, Typography, Button, Tabs, Tab, Paper } from '@mui/material';
import { useAuth } from '../contexts/AuthContext';
import ChangePasswordModal from '../components/Modals/Usuarios/ChangePasswordModal';
import { useNavigate, useLocation } from 'react-router-dom'; // Para manejar la navegación y la ruta actual

interface MainLayoutProps {
    children: ReactNode;
}

const modules = [
    { label: 'Inicio', path: '/' },
    { label: 'Distribución', path: '/distribucion' },
    { label: 'Contables', path: '/contables' },
    { label: 'Impresión', path: '/impresion' },
    { label: 'Reportes', path: '/reportes' },
    { label: 'Radios', path: '/radios' },
    { label: 'Usuarios', path: '/usuarios' },
];


const MainLayout: React.FC<MainLayoutProps> = ({ children }) => {
    const {
        user,
        logout,
        // ... (resto de las props de useAuth) ...
        isAuthenticated,
        isPasswordChangeForced,
        showForcedPasswordChangeModal,
        setShowForcedPasswordChangeModal,
        passwordChangeCompleted
    } = useAuth();

    const navigate = useNavigate();
    const location = useLocation(); // Para obtener la ruta actual

    const [selectedTab, setSelectedTab] = useState<number | false>(false);

    useEffect(() => {
        const currentModulePath = modules.findIndex(module =>
            location.pathname === module.path || (module.path !== '/' && location.pathname.startsWith(module.path + '/'))
        );
        if (currentModulePath !== -1) {
            setSelectedTab(currentModulePath);
        } else if (location.pathname === '/') {
            setSelectedTab(0);
        } else {
            setSelectedTab(false);
        }
    }, [location.pathname]);

    const handleModalClose = (passwordChangedSuccessfully: boolean) => {
        if (passwordChangedSuccessfully) {
            passwordChangeCompleted();
        } else {
            if (isPasswordChangeForced) {
                logout();
            } else {
                setShowForcedPasswordChangeModal(false);
            }
        }
    };

    const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
        setSelectedTab(newValue);
        navigate(modules[newValue].path);
    };

    // Determinar si el módulo actual es el de Reportes
    const isReportesModule = location.pathname.startsWith('/reportes');

    if (showForcedPasswordChangeModal && isPasswordChangeForced) {
        // ... (lógica del modal forzado sin cambios) ...
        return (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}>
                <ChangePasswordModal
                    open={showForcedPasswordChangeModal}
                    onClose={handleModalClose}
                    isFirstLogin={isPasswordChangeForced}
                />
            </Box>
        );
    }

    return (
        <Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
            <AppBar position="static">
                {/* ... (Toolbar y Tabs sin cambios) ... */}
                <Toolbar>
                    <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
                        Sistema de Gestión - El Día
                    </Typography>
                    {user && <Typography sx={{ mr: 2 }}>Hola, {user.nombreCompleto}</Typography>}
                    {isAuthenticated && !isPasswordChangeForced && (
                        <Button
                            color="inherit"
                            onClick={() => setShowForcedPasswordChangeModal(true)}
                        >
                            Cambiar Contraseña
                        </Button>
                    )}
                    <Button color="inherit" onClick={logout}>Cerrar Sesión</Button>
                </Toolbar>
                <Paper square elevation={0} >
                    <Tabs
                        value={selectedTab}
                        onChange={handleTabChange}
                        indicatorColor="secondary"
                        textColor="inherit"
                        variant="scrollable"
                        scrollButtons="auto"
                        aria-label="módulos principales"
                        sx={{ backgroundColor: 'primary.main', color: 'white' }}
                    >
                        {modules.map((module) => (
                            <Tab key={module.path} label={module.label} />
                        ))}
                    </Tabs>
                </Paper>
            </AppBar>

            {/* Contenido del Módulo */}
            <Box
                component="main"
                sx={{
                    flexGrow: 1,
                    py: isReportesModule ? 0 : 3, // Padding vertical condicional. Si es el módulo de Reportes, px es 0 si no 3
                    px: isReportesModule ? 0 : 3, // Padding horizontal condicional. Si es el módulo de Reportes, px es 0 si no 3
                    display: 'flex', // IMPORTANTE: Para que el hijo (ReportesIndexPage) pueda usar height: '100%'
                    flexDirection: 'column' // IMPORTANTE
                }}
            >
                {children}
            </Box>

            <Box component="footer" sx={{ p: 1, mt: 'auto', backgroundColor: 'primary.dark', color: 'white', textAlign: 'center' }}>
                <Typography variant="body2">
                    Usuario: {user?.username} | Acceso: {user?.esSuperAdmin ? 'Super Admin' : `Perfil ID ${user?.userId}`} | Versión: {/* TODO: Obtener versión */}
                </Typography>
            </Box>

            <ChangePasswordModal
                open={showForcedPasswordChangeModal}
                onClose={handleModalClose}
                isFirstLogin={isPasswordChangeForced}
            />
        </Box>
    );
};

export default MainLayout;