import { Tab } from '@mui/material'
import { ChangeEvent, useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { StyledTabs, StyledTabsWrapper } from './styles'

interface TabsContainerProps {
  tabs: {
    key: string
    label: string
    onClick: (tab?: { label: string; value: any }) => void
  }[]
  size?: 'small' | 'medium'
}

export default function Tabs({ tabs, size = 'small' }: TabsContainerProps) {
  const match: any = useLocation()
  let pathArray = match.pathname.split('/')
  const [currentTab, setCurrentTab] = useState(tabs[0].key)

  const handleTabsChange = (_event: ChangeEvent<{}>, value: string): void => {
    setCurrentTab(value)
  }
  useEffect(() => {
    let currentPosition = tabs.find(
      (tab) => tab.key == `/${pathArray[pathArray.length - 2]}/`,
    )

    setCurrentTab(currentPosition?.key ? currentPosition.key : tabs[0].key)
  }, [])

  return (
    <StyledTabsWrapper>
      <StyledTabs
        size={size}
        onChange={handleTabsChange}
        value={currentTab}
        variant="scrollable"
        scrollButtons="auto"
        textColor="primary"
        indicatorColor="primary"
      >
        {tabs.map((tab) => (
          <Tab
            key={tab.key}
            label={tab.label}
            value={tab.key}
            onClick={() => tab.onClick({ label: tab.label, value: tab.key })}
          />
        ))}
      </StyledTabs>
    </StyledTabsWrapper>
  )
}
