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

const radiosSubModules = [
  { label: 'Generar Listas', path: 'generar-listas' },
  { label: 'Ritmos', path: 'ritmos' },
  { label: 'Canciones', path: 'canciones' },  
];

const RadiosIndexPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedSubTab, setSelectedSubTab] = useState<number>(0); // Inicializa en 0

  useEffect(() => {
    const currentBasePath = '/radios';
    const subPath = location.pathname.startsWith(currentBasePath + '/')
      ? location.pathname.substring(currentBasePath.length + 1).split('/')[0]
      : undefined;

    const activeTabIndex = radiosSubModules.findIndex(sm => sm.path === subPath);

    if (location.pathname === currentBasePath) {
      // Si está en /radios, redirige a la primera subruta
      navigate(radiosSubModules[0].path, { replace: true });
      setSelectedSubTab(0);
    } else if (activeTabIndex !== -1) {
      setSelectedSubTab(activeTabIndex);
    }
  }, [location.pathname, navigate]);

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

  return (
    <Box>
      <Typography variant="h5" gutterBottom>Módulo de Radios</Typography>
      <Paper square elevation={1}>
        <Tabs value={selectedSubTab} onChange={handleSubTabChange} indicatorColor="primary" textColor="primary" variant="scrollable" scrollButtons="auto">
          {radiosSubModules.map((subModule) => (
            <Tab key={subModule.path} label={subModule.label} />
          ))}
        </Tabs>
      </Paper>
      <Box sx={{ pt: 2 }}>
        <Outlet />
      </Box>
    </Box>
  );
};
export default RadiosIndexPage;