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

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);
  const { isSuperAdmin } = usePermissions();

  // --- Filtrar solo lo que puede ver este usuario ---
  const availableSubModules = useMemo(
    () =>
      usuariosSubModules.filter(sub => {
        // Estos dos ítems solo para superadmins
        if (
          (sub.path === 'permisos' || sub.path === 'auditoria-usuarios')
          && !isSuperAdmin
        ) {
          return false;
        }
        return true;
      }),
    [isSuperAdmin]
  );

  // --- Ajustar la pestaña activa según la ruta ---
  useEffect(() => {
    const base = '/usuarios';
    let subPath: string | undefined;
    if (location.pathname.startsWith(base + '/')) {
      subPath = location.pathname.slice(base.length + 1).split('/')[0];
    } else if (location.pathname === base) {
      subPath = availableSubModules[0]?.path;
    }
    const idx = availableSubModules.findIndex(m => m.path === subPath);
    if (idx !== -1) {
      setSelectedSubTab(idx);
    } else if (location.pathname === base && availableSubModules.length) {
      navigate(availableSubModules[0].path, { replace: true });
      setSelectedSubTab(0);
    } else {
      setSelectedSubTab(false);
    }
  }, [location.pathname, navigate, availableSubModules]);

  const handleSubTabChange = (_: any, newValue: number) => {
    setSelectedSubTab(newValue);
    navigate(availableSubModules[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"
        >
          {availableSubModules.map(sub => (
            <Tab key={sub.path} label={sub.label} />
          ))}
        </Tabs>
      </Paper>
      <Box sx={{ pt: 2 }}>
        <Outlet />
      </Box>
    </Box>
  );
};

export default UsuariosIndexPage;
