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

// Define las sub-pestañas del módulo Impresión
const impresionSubModules = [
  { label: 'Stock Bobinas', path: 'stock-bobinas' },
  { label: 'Tiradas', path: 'tiradas' },
  { label: 'Plantas', path: 'plantas' },
  { label: 'Tipos Bobina', path: 'tipos-bobina' },
  { label: 'Estados Bobina', path: 'estados-bobina' },  
];

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

  useEffect(() => {
       const currentBasePath = '/impresion';
       const defaultSubPath = 'stock-bobinas'; // Define tu sub-ruta por defecto aquí
  
       const pathParts = location.pathname.split('/');
       const currentSubPathSegment = pathParts[2]; // /impresion -> pathParts[1] es 'impresion', pathParts[2] sería la sub-ruta
  
       let activeTabIndex = -1;
  
       if (currentSubPathSegment) {
           activeTabIndex = impresionSubModules.findIndex(
               (subModule) => subModule.path === currentSubPathSegment
           );
       }
       
       if (activeTabIndex !== -1) {
           setSelectedSubTab(activeTabIndex);
       } else {
           // Si estamos en la ruta base /impresion o una subruta no reconocida
           if (location.pathname === currentBasePath || (location.pathname.startsWith(currentBasePath) && activeTabIndex === -1) ) {
               const defaultTabIndex = impresionSubModules.findIndex(sm => sm.path === defaultSubPath);
               if (defaultTabIndex !== -1) {
                   navigate(`${currentBasePath}/${defaultSubPath}`, { replace: true });
                   setSelectedSubTab(defaultTabIndex);
               } else if (impresionSubModules.length > 0) { // Fallback al primero si el default no existe
                   navigate(`${currentBasePath}/${impresionSubModules[0].path}`, { replace: true });
                   setSelectedSubTab(0);
               } else {
                   setSelectedSubTab(false); // No hay sub-módulos
               }
           } else {
               setSelectedSubTab(false); // No es una ruta del módulo contable
           }
       }
   }, [location.pathname, navigate]);

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

  return (
    <Box>
      <Typography variant="h5" gutterBottom>Módulo de Impresión</Typography>
      <Paper square elevation={1}>
        <Tabs
          value={selectedSubTab}
          onChange={handleSubTabChange}
          indicatorColor="primary"
          textColor="primary"
          variant="scrollable"
          scrollButtons="auto"
          aria-label="sub-módulos de impresión"
        >
          {impresionSubModules.map((subModule) => (
            <Tab key={subModule.path} label={subModule.label} />
          ))}
        </Tabs>
      </Paper>
      <Box sx={{ pt: 2 }}>
        <Outlet /> {/* Renderizará GestionarPlantasPage, etc. */}
      </Box>
    </Box>
  );
};

export default ImpresionIndexPage;