import React, { useState, useEffect } from 'react';
import { Box, Tabs, Tab, Paper, Typography } from '@mui/material';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';

const usuariosSubModules = [
  { label: 'Perfiles', path: 'perfiles' },
  { label: 'Permisos (Definición)', path: 'permisos' },
  { label: 'Usuarios', path: 'gestion-usuarios' },
  { label: 'Auditoría Usuarios', path: 'auditoria-usuarios' },
];

const UsuariosIndexPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedSubTab, setSelectedSubTab] = useState<number | false>(false);

  useEffect(() => {
    const currentBasePath = '/usuarios';
    const subPath = location.pathname.startsWith(currentBasePath + '/')
                      ? location.pathname.substring(currentBasePath.length + 1).split('/')[0] // Tomar solo la primera parte de la subruta
                      : (location.pathname === currentBasePath ? usuariosSubModules[0]?.path : undefined);

    const activeTabIndex = usuariosSubModules.findIndex(
      (subModule) => subModule.path === subPath
    );

    if (activeTabIndex !== -1) {
      setSelectedSubTab(activeTabIndex);
    } else {
       if (location.pathname === currentBasePath && usuariosSubModules.length > 0) {
         navigate(usuariosSubModules[0].path, { replace: true });
         setSelectedSubTab(0);
       } else {
          setSelectedSubTab(false);
       }
    }
  }, [location.pathname, navigate]);

  const handleSubTabChange = (_event: React.SyntheticEvent, newValue: number) => {
    setSelectedSubTab(newValue);
    navigate(usuariosSubModules[newValue].path);
  };

  return (
    <Box>
      <Typography variant="h5" gutterBottom>Módulo de Usuarios y Seguridad</Typography>
      <Paper square elevation={1}>
        <Tabs
          value={selectedSubTab}
          onChange={handleSubTabChange}
          indicatorColor="primary"
          textColor="primary"
          variant="scrollable"
          scrollButtons="auto"
          aria-label="sub-módulos de usuarios"
        >
          {usuariosSubModules.map((subModule) => (
            <Tab key={subModule.path} label={subModule.label} />
          ))}
        </Tabs>
      </Paper>
      <Box sx={{ pt: 2 }}>
        <Outlet />
      </Box>
    </Box>
  );
};

export default UsuariosIndexPage;