import React, { useRef, useEffect, useCallback,useMemo} from "react";
import {Tooltip,Tabs,Tab, Box} from "@mui/material";
import { AutoHeightContainer } from "@/widgetLibrary/PublicSector/AutoHeightContainer";
import { getComponentMap } from "@/redux/currentApp/components/componentsSelector"
import { useSelector } from "react-redux"
import { get } from "lodash-es"

export const TabPanel = ({
  currentIndex,
  viewList,
  tabList,
  triggerEventHandler,
  handleUpdateMultiExecutionResult,
  linkWidgetDisplayName,
  displayName,
  updateComponentRuntimeProps,
  tooltipText,
  orientation,
  updateComponentHeight,
  colorScheme,
  disabled,
  navigateContainer
}) => {
  const [value, setValue] = React.useState(0);
  const components = useSelector(getComponentMap)


  const handleChange = (newValue) => {
    setValue(newValue);
  };

  const preCurrentViewIndex = useRef<number>(currentIndex);

  useEffect(() => {
    if (typeof preCurrentViewIndex.current !== "number") {
      preCurrentViewIndex.current = currentIndex;
    }
    if (preCurrentViewIndex.current !== currentIndex) {
      triggerEventHandler("change");
      preCurrentViewIndex.current = currentIndex;
    }
  }, [currentIndex, triggerEventHandler]);

  const handleUpdateOriginalDSLAttrs = useCallback(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (updateSlice: Record<string, any>) => {
      handleUpdateMultiExecutionResult([
        {
          displayName,
          value: updateSlice,
        },
      ]);
      if (linkWidgetDisplayName && linkWidgetDisplayName.length > 0) {
        const curUpdateSlice = linkWidgetDisplayName.map((name) => ({
          displayName: name,
          value: updateSlice,
        }));

        handleUpdateMultiExecutionResult(curUpdateSlice);
      }
    },
    [displayName, handleUpdateMultiExecutionResult, linkWidgetDisplayName]
  );

  const handleUpdateExecution = useCallback(
    (updateSliceItem: any) => {
      if (navigateContainer && linkWidgetDisplayName) {
        handleUpdateMultiExecutionResult([
          {
            displayName: linkWidgetDisplayName,
            value: updateSliceItem,
          },
        ])
        const targetLinkedDisplayNames = get(
          components,
          `${linkWidgetDisplayName}.props.linkWidgetDisplayName`,
          [],
        )
        if (Array.isArray(targetLinkedDisplayNames)) {
          const curUpdateSliceItem = targetLinkedDisplayNames
            .filter((name) => name !== displayName)
            .map((name) => ({
              displayName: name,
              value: updateSliceItem,
            }))
          handleUpdateMultiExecutionResult(curUpdateSliceItem)
        }
        targetLinkedDisplayNames &&
          Array.isArray(targetLinkedDisplayNames) &&
          targetLinkedDisplayNames.forEach((targetLinkedDisplayName) => {
            targetLinkedDisplayName !== displayName &&
              handleUpdateMultiExecutionResult([
                {
                  displayName: targetLinkedDisplayName,
                  value: updateSliceItem,
                },
              ])
          })
      }

      handleUpdateMultiExecutionResult([
        {
          displayName,
          value: updateSliceItem,
        },
      ])
    },
    [
      components,
      displayName,
      handleUpdateMultiExecutionResult,
      linkWidgetDisplayName,
      navigateContainer,
    ],
  )

  useEffect(() => {
    updateComponentRuntimeProps?.({
      setCurrentViewKey: (key: string) => {
        const index = viewList.findIndex((viewItem) => viewItem.key === key);
        if (index === -1) return;
        handleUpdateOriginalDSLAttrs({
          currentIndex: index,
          currentKey: key,
        });
      },
      setCurrentViewIndex: (index: string) => {
        const numberIndex = parseInt(index);
        const view = viewList[numberIndex];
        if (!view) return;
        handleUpdateOriginalDSLAttrs({
          currentIndex: numberIndex,
          currentKey: view.key,
        });
      },
      showNextView: (loop: boolean) => {
        let newCurrentIndex = currentIndex + 1;
        if (newCurrentIndex >= viewList.length) {
          if (!loop) return;
          newCurrentIndex = 0;
        }
        const currentView = viewList[newCurrentIndex];
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
      showNextVisibleView: (loop: boolean) => {
        let newCurrentIndex = currentIndex + 1;
        if (newCurrentIndex >= viewList.length) {
          if (!loop) return;
          newCurrentIndex = 0;
        }
        let currentView = viewList[newCurrentIndex];
        while (currentView.hidden || currentView.disabled) {
          newCurrentIndex++;
          currentView = viewList[newCurrentIndex];
          if (newCurrentIndex >= viewList.length) {
            if (!loop) return;
            newCurrentIndex = 0;
          }
        }
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
      showPreviousView: (loop: boolean) => {
        let newCurrentIndex = currentIndex - 1;

        if (newCurrentIndex < 0) {
          if (!loop) return;
          newCurrentIndex = viewList.length - 1;
        }
        const currentView = viewList[newCurrentIndex];
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
      showPreviousVisibleView: (loop: boolean) => {
        let newCurrentIndex = currentIndex - 1;

        if (newCurrentIndex < 0) {
          if (!loop) return;
          newCurrentIndex = viewList.length - 1;
        }
        let currentView = viewList[newCurrentIndex];
        while (currentView.hidden || currentView.disabled) {
          newCurrentIndex--;
          currentView = viewList[newCurrentIndex];
          if (newCurrentIndex < 0) {
            if (!loop) return;
            newCurrentIndex = viewList.length - 1;
          }
        }
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
    });
    // return () => {
    //   deleteComponentRuntimeProps()
    // }
  }, [
    // deleteComponentRuntimeProps,
    updateComponentRuntimeProps,
    handleUpdateOriginalDSLAttrs,
    viewList,
    currentIndex,
  ]);

  const list = useMemo(() => {
    if (navigateContainer) return viewList
    return tabList
  }, [navigateContainer, tabList, viewList])


  return (
    <>
  <Box  sx={{ width: '100%' }}>
    <Tooltip title={tooltipText}>
      <Tabs
      
        orientation={orientation}
        // variant="scrollable"
        value={value}
        onChange={(_,value) => {
          new Promise((resolve) => {
            const currentIndex = value;

            handleUpdateExecution?.({
              currentKey: value,
              currentIndex,
            })
            resolve(true)
          }).then(() => {
            handleChange(value)
          })
        }}
        aria-label="Vertical tabs example"
        sx={{ 
            
            '& .Mui-selected': { 
              color: colorScheme, 
              backgroundColor: 'white',
            },
          }}
      >
        {list.map(({ label, id }) => (
          <Tab label={label} id={id} disabled={disabled}/>
        ))}
      </Tabs>
      </Tooltip>
      </Box>
    </>
  );
};
