// src/pages/contables/ContablesIndexPage.tsx
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 Contables
const contablesSubModules = [
  { label: 'Pagos Distribuidores', path: 'pagos-distribuidores' },
  { label: 'Notas Crédito/Débito', path: 'notas-cd' },
  { label: 'Gestión de Saldos', path: 'gestion-saldos' },
  { label: 'Tipos de Pago', path: 'tipos-pago' },
  { label: 'Cierres CC', path: 'cierres-cc' },
];

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

  useEffect(() => {
     const currentBasePath = '/contables';
     const defaultSubPath = 'pagos-distribuidores'; // Define tu sub-ruta por defecto aquí

     const pathParts = location.pathname.split('/');
     const currentSubPathSegment = pathParts[2]; // /contables -> pathParts[1] es 'contables', pathParts[2] sería la sub-ruta

     let activeTabIndex = -1;

     if (currentSubPathSegment) {
         activeTabIndex = contablesSubModules.findIndex(
             (subModule) => subModule.path === currentSubPathSegment
         );
     }
     
     if (activeTabIndex !== -1) {
         setSelectedSubTab(activeTabIndex);
     } else {
         // Si estamos en la ruta base /contables o una subruta no reconocida
         if (location.pathname === currentBasePath || (location.pathname.startsWith(currentBasePath) && activeTabIndex === -1) ) {
             const defaultTabIndex = contablesSubModules.findIndex(sm => sm.path === defaultSubPath);
             if (defaultTabIndex !== -1) {
                 navigate(`${currentBasePath}/${defaultSubPath}`, { replace: true });
                 setSelectedSubTab(defaultTabIndex);
             } else if (contablesSubModules.length > 0) { // Fallback al primero si el default no existe
                 navigate(`${currentBasePath}/${contablesSubModules[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(contablesSubModules[newValue].path);
  };

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

export default ContablesIndexPage;