import React, { ComponentProps, forwardRef, useEffect, useRef, useState } from 'react';
import { Tabs as MuiTabs, tabsClasses } from '@mui/material';
import { useTheme } from '@mui/material/styles';

import { countValidChildren } from '@/mui/helpers';

type Props = {} & ComponentProps<typeof MuiTabs>;

const Tabs = forwardRef<HTMLElement, Props>((props, ref) => {
  const theme = useTheme();
  const localRef = useRef<HTMLDivElement | null>(null);
  const [scrollGradient, setScrollGradient] = useState(theme.palette.background.default);

  useEffect(() => {
    const getRecursiveBackgroundColor = (element: HTMLElement | null): string => {
      if (!element) return theme.palette.background.default;

      const { backgroundColor } = window.getComputedStyle(element);
      if (backgroundColor !== 'rgba(0, 0, 0, 0)' && backgroundColor !== 'transparent') {
        return backgroundColor;
      }

      return getRecursiveBackgroundColor(element.parentElement);
    };

    setScrollGradient(getRecursiveBackgroundColor(localRef.current));
  }, [theme]);

  const childrenCount = countValidChildren(props.children);

  return (
    <MuiTabs
      {...props}
      ref={(node) => {
        if (typeof ref === 'function') {
          ref(node);
        } else if (ref) {
          ref.current = node;
        }
        localRef.current = node;
      }}
      variant={props.variant !== 'fullWidth' && childrenCount <= 1 ? 'standard' : props.variant}
      sx={{
        '--internal-scroll-gradient': scrollGradient,
        ...(props.indicatorColor && {
          [`.${tabsClasses.indicator}`]: {
            backgroundColor: theme.palette[props.indicatorColor].main,
          },
        }),
        ...props.sx,
      }}
    />
  );
});

Tabs.displayName = 'Tabs';

export default Tabs;
