import { Tab } from '@mui/material'
import { ChangeEvent, ReactNode, useEffect, useState } from 'react'
import ErrorBoundary from '../ErrorBoundary'
import { StyledComponentWrapper, StyledContainer, StyledTabs } from './styles'

export interface TabsContainerProps {
  tabs: {
    key: string
    label: string
    component: ReactNode
    highlight?: boolean
  }[]
  size?: 'small' | 'medium'
  containerVariant?: 'box' | 'page'
  onTabChange?: (tabKey: string) => void
  tabUnderlineColor?: string
  tabMobileUnderlineColor?: string
  currentTabIndex?: number
}

export default function TabsContainer({
  tabs,
  size = 'small',
  containerVariant = 'box',
  onTabChange,
  tabUnderlineColor,
  tabMobileUnderlineColor,
  currentTabIndex = 0,
}: TabsContainerProps) {
  const [currentTab, setCurrentTab] = useState(tabs[currentTabIndex]?.key)

  const handleTabsChange = (_event: ChangeEvent<{}>, value: string): void => {
    setCurrentTab(value)
    onTabChange && onTabChange(value)
  }
  useEffect(() => {
    setCurrentTab(tabs[currentTabIndex]?.key)
  }, [])

  return (
    <StyledContainer>
      <StyledTabs
        containerVariant={containerVariant}
        size={size}
        onChange={handleTabsChange}
        value={currentTab}
        variant="scrollable"
        scrollButtons="auto"
        textColor="primary"
        indicatorColor="primary"
        underlineColor={tabUnderlineColor}
        mobileUnderlineColor={tabMobileUnderlineColor}
      >
        {tabs.map((tab) => (
          <Tab
            key={tab?.key}
            label={tab.label}
            value={tab?.key}
            icon={tab.highlight ? <span>{'.'}</span> : null}
            iconPosition="end"
          />
        ))}
      </StyledTabs>
      <StyledComponentWrapper containerVariant={containerVariant}>
        <ErrorBoundary>
          {tabs.find((tab) => tab?.key === currentTab)?.component}
        </ErrorBoundary>
      </StyledComponentWrapper>
    </StyledContainer>
  )
}
