import React, { FC, useState, forwardRef, useImperativeHandle } from "react";
import { Box, Divider, Tabs as TabsMui } from "@mui/material";
import { TabContainer } from "./TabContainer";
import { createTab } from "./Tab";
import { TabsProps } from "./types";
import "./style.scss";

export const Tabs: FC<TabsProps> = forwardRef(({ children, tab = 0, onChange, delay = 0, isLoading = false }, ref) => {
  const [value, setValue] = useState(tab);
  const [isChanging, setIsChanging] = useState(false);


  const onChangeTab = (tabNumber: number = 0) => {
    if (tabNumber < 0 || isChanging || isLoading) return;
    onChange && onChange(tabNumber)
    setValue(tabNumber);
    setIsChanging(true);
    setTimeout(() => {
      setIsChanging(false);
    }, delay);
  };

  useImperativeHandle(ref, () => ({
    setValue: setValue
  }));

  return (
    <Box sx={{ opacity: isLoading ? 0.6 : 1, pointerEvents: isLoading ? "none" : "auto" }}>
      <TabsMui
        value={value}
        onClick={(e) => onChangeTab((e.target as HTMLInputElement).tabIndex)}
        variant="scrollable"
        style={{ padding: "16px" }}
        className="tab-gtc-rc"
      >
        {createTab(children)}
      </TabsMui>
      <Divider style={{ marginTop: "-17px" }} />
      {children.map((item: JSX.Element, index: number) => {
        return (
          <TabContainer key={index} {...item.props} value={value}>
            {item.props.children}
          </TabContainer>
        );
      })}
    </Box>
  );
});
