import React, { SyntheticEvent } from 'react';
import { Box, SxProps } from '@mui/material';
import { ColorVariant, DataTabs, MuiTabsBaseProps, TabsVariant } from '@/types';
import { NormaTab, NormaTabs } from './UncontrolledTabs.style';
import { Theme } from '@emotion/react';
import { NormaTabInfo } from './UncontrolledTabsInfo.style';

interface Props extends MuiTabsBaseProps {
  sx?: SxProps<Theme>;
  tabs: DataTabs[];
  tab: number;
  onTabChange: (event: SyntheticEvent, tab: number) => void;
  color?: ColorVariant;
  variant?: TabsVariant;
  info?: React.ReactNode;
  tabPanelSx?: SxProps<Theme>;
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
  sx?: SxProps<Theme>;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, sx, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ p: 3, ...sx }}>{children}</Box>}
    </div>
  );
}

function a11yProps(index: number) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const UncontrolledTabs = ({ tabs, tab, color = 'primary', onTabChange, info, ...props }: Props) => {
  const handleChange = (event: SyntheticEvent, newValue: number) => {
    onTabChange(event, newValue);
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Box>
        <NormaTabs value={tab} color={color} onChange={handleChange} aria-label="tabs" {...props}>
          {tabs.map((item, key) => (
            <NormaTab key={key} label={item.label} {...a11yProps(key)} />
          ))}
          {info && <NormaTabInfo>{info}</NormaTabInfo>}
        </NormaTabs>
      </Box>
      {tabs.map((item, key) => (
        <TabPanel {...item.tabPanel?.props} key={key} value={tab} index={key} sx={props.tabPanelSx}>
          {item.children}
        </TabPanel>
      ))}
    </Box>
  );
};

export default UncontrolledTabs;
