import { Box, Tabs as MuiTabs, Tab } from '@mui/material';
import { styled, ThemeOptions, useTheme } from '@mui/material/styles';
import React from 'react';
import { TabPanelProps, TabsBaseProps } from '../interfaces';

const TabsStyled = styled(MuiTabs)<{
  theme: ThemeOptions;
}>(({ theme }) => ({
  borderBottom: '1px solid #e8e8e8',
  '& .Mui-selected': {
    color: theme.palette.primary.main,
  },
  '& .MuiTabs-indicator': {
    backgroundColor: theme.palette.primary.main,
  },
  '& .MuiButtonBase-root': {
    textTransform: 'none',
  },
}));

interface StyledTabProps {
  label: string;
}

const TabStyled = styled((props: StyledTabProps) => <Tab disableRipple {...props} />)(({ theme }) => ({
  textTransform: 'none',
  fontWeight: theme.typography.fontWeightRegular,
  fontSize: theme.typography.pxToRem(15),
  marginRight: theme.spacing(1),
  color: theme.palette.text.secondary,
  padding: '5px 15px',
  top: '5px',
  minWidth: '60px',
  '&.Mui-selected': {
    color: theme.palette.primary.main,
  },
  '&.Mui-focusVisible': {
    backgroundColor: 'rgba(100, 95, 228, 0.32)',
  },
}));

function CustomTabPanel(props: TabPanelProps) {
  const { children, value, index, ...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 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

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

export const Tabs = ({ data = [], color = 'primary', onChange, ...props }: TabsBaseProps) => {
  const muiTheme = useTheme()
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
    if(!!onChange) onChange(event, newValue)
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Box>
        <TabsStyled value={value} onChange={handleChange} aria-label="basic tabs example" {...props} theme={muiTheme}>
          {data && data.map((item, key) => <TabStyled label={item.label} {...a11yProps(key)} />)}
        </TabsStyled>
      </Box>
      {data &&
        data.map((item, key) => (
          <CustomTabPanel value={value} index={key} key={key}>
            {item.children}
          </CustomTabPanel>
        ))}
    </Box>
  );
};
