import React from 'react'
import { Tabs, Tab, Box } from '@mui/material'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '../store'

interface NavigationTabsProps {
  currentPath: string
}

export const NavigationTabs: React.FC<NavigationTabsProps> = ({ currentPath }) => {
  const navigate = useNavigate()
  const { currentDocument, extractionById } = useAppSelector((state) => state.document)

  const tabs = [
    { label: 'Téléversement', path: '/', alwaysEnabled: true },
    { label: 'Extraction', path: '/extraction', alwaysEnabled: true },
    { label: 'Contexte', path: '/contexte', alwaysEnabled: false },
    { label: 'Conseil', path: '/conseil', alwaysEnabled: false },
  ]

  const currentTabIndex = tabs.findIndex(tab => tab.path === currentPath)

  // Vérifier si au moins une extraction est terminée
  const hasCompletedExtraction = currentDocument && extractionById[currentDocument.id]

  const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
    const tab = tabs[newValue]
    if (tab.alwaysEnabled || hasCompletedExtraction) {
      navigate(tab.path)
    }
  }

  return (
    <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
      <Tabs
        value={currentTabIndex >= 0 ? currentTabIndex : 0}
        onChange={handleTabChange}
        aria-label="navigation tabs"
        variant="scrollable"
        scrollButtons="auto"
      >
        {tabs.map((tab, index) => (
          <Tab
            key={index}
            label={tab.label}
            disabled={!tab.alwaysEnabled && !hasCompletedExtraction}
            sx={{
              opacity: (!tab.alwaysEnabled && !hasCompletedExtraction) ? 0.5 : 1,
              '&.Mui-disabled': {
                color: 'text.disabled'
              }
            }}
          />
        ))}
      </Tabs>
    </Box>
  )
}
