import * as React from "react";
import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";
import isEmpty from "lodash/isEmpty";
import { ArrayControlProps, UISchemaElement } from "@jsonforms/core";
import Box from "@mui/material/Box";
import { JsonFormsDispatch, useJsonForms } from "@jsonforms/react";
import { DataContext } from "../context/Context";
import { Divider, Typography } from "@mui/material";

interface TabPanelProps {
  children: any;
  index: number;
  value: number;
  id: number | string;
  theme: any;
  uischema: any;
}
function TabPanel(props: TabPanelProps) {
  const { children, value, index, id, theme, uischema, ...other } = props;
  return (
    <div
      role="tabpanel"
      key={id}
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      <Box
        key={id}
        sx={{
          p: 0,
          pr: 0,
          ...theme?.TabPanelStyle,
          ...uischema?.config?.style?.TabPanelStyle,
        }}
      >
        {children}
      </Box>
    </div>
  );
}
function a11yProps(index: number) {
  return {
    id: `simple-tab-${index}`,
    "aria-controls": `simple-tabpanel-${index}`,
  };
}
export default function TabLayout({
  elements,
  path,
  schema,
  uischema,
  renderers,
  enabled,
  cells,
}: ArrayControlProps & any) {
  const [value, setValue] = React.useState(0);
  const { pageName } = React.useContext(DataContext);
  const MainVariables = uischema.config?.main;
  const ConfigStyles = uischema.config?.style;
  const isVertical = MainVariables?.orientation === "vertical";
  const tabLength = MainVariables?.tabLabels.length;
  React.useEffect(() => {
    setValue(0);
  }, [MainVariables?.id, path, pageName]);
  const { theme } = React.useContext(DataContext);
  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };
  const getTabStyles = (index: number) => ({
    ...theme.TabStyle,
    borderBottom: isVertical ? "1px solid rgba(0, 0, 0, 0.12)" : undefined,
    marginLeft: "24px",
    position: "relative",
    overflow: "visible",
    minWidth: "0px",
    textTransform: "none",
    ...(index !== tabLength - 1 && {
      "&::after": {
        content: '""',
        position: "absolute",
        top: 15,
        right: "-12px",
        height: "calc(70% - 8px)",
        width: "3px",
        backgroundColor: "#707070",
        opacity: 0.26,
      },
    }),
    ...ConfigStyles?.TabsHeaderStyle,
  });
  const tabsAndPanels = (
    <>
      <Tabs
        orientation={MainVariables?.orientation}
        id={path}
        variant="scrollable"
        sx={{
          ...theme.TabsStyle,
          borderRight: isVertical ? 1 : undefined,
          borderColor: isVertical ? "divider" : undefined,
          borderTopRightRadius: isVertical ? "0px" : undefined,
          paddingTop: isVertical ? "30px" : undefined,
          minWidth: isVertical ? "100px" : undefined,
          ...uischema?.config?.TabsStyle,
          ...ConfigStyles?.TabsStyle,
        }}
        value={value}
        onChange={handleChange}
        aria-label="basic tabs example"
      >
        {uischema.tabLabelElements?.length > 0
          ? uischema.tabLabelElements.map((elem: any, index: number) => (
              <Tab
                key={`tabsKey-${elem}`}
                sx={getTabStyles(index)}
                label={
                  <JsonFormsDispatch
                    schema={schema}
                    uischema={elem}
                    path={path}
                    cells={cells}
                    renderers={renderers}
                  />
                }
                {...a11yProps(index)}
              />
            ))
          : MainVariables?.tabLabels.map((elem: string, index: number) => {
              return (
                <Tab
                  key={`tabsKey-${elem}`}
                  disabled={MainVariables?.disabledTabs?.elem || false}
                  sx={getTabStyles(index)}
                  label={elem}
                  {...a11yProps(index)}
                />
              );
            })}
      </Tabs>
      <Box
        sx={{
          width: isVertical ? "100%" : undefined,
          overflow: isVertical ? "auto" : undefined,
        }}
      >
        {!isEmpty(elements) && uischema?.config?.main?.lazyLoad ? (
          <TabPanel
            value={value}
            index={value}
            key={`keyPanel-${value}`}
            id={`keyPanel-${value}`}
            theme={theme}
            uischema={uischema}
          >
            <JsonFormsDispatch
              schema={schema}
              uischema={elements[value]}
              enabled={enabled}
              renderers={renderers}
              cells={cells}
            />
          </TabPanel>
        ) : (
          elements.map((e, i) => {
            return (
              <TabPanel
                value={value}
                index={i}
                key={`keyPanel-${i}`}
                id={`keyPanel-${i}`}
                theme={theme}
                uischema={uischema}
              >
                <JsonFormsDispatch
                  schema={schema}
                  uischema={e}
                  enabled={enabled}
                  renderers={renderers}
                  cells={cells}
                />
              </TabPanel>
            );
          })
        )}
      </Box>
    </>
  );
  return (
    <Box
      key={location.pathname}
      sx={{
        ...theme.TabContainerStyle,
        ...uischema?.config?.style?.TabContainerStyle,
        flexGrow: isVertical ? 1 : undefined,
        display: isVertical ? "flex" : undefined,
      }}
    >
      {uischema?.config?.main?.label && (
        <Box>
          <Typography
            component={"div"}
            sx={{
              padding: "10px",
              paddingLeft: "28px",
              fontSize: { xs: "16px", sm: "20px" },
              fontWeight: 500,
              ...uischema?.config?.style?.labelStyle,
            }}
          >
            {uischema.config?.main?.label}
          </Typography>
          {uischema?.config?.main?.divider && (
            <Divider sx={{ paddingTop: "8px" }} variant="fullWidth"></Divider>
          )}
        </Box>
      )}
      {isVertical ? tabsAndPanels : <Box>{tabsAndPanels}</Box>}
    </Box>
  );
}
export const CustomTabLayout = React.memo(TabLayout);
