import { Box, Skeleton, SxProps } from '@mui/material';
import React, {
  useEffect,
  useRef,
  useState,
  Children,
  cloneElement,
  isValidElement,
  ReactElement,
  useLayoutEffect,
} from 'react';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { InfoRowGroupContext } from '../contexts/info-row';

type InfoRowGroupProps = {
  children: React.ReactNode;
  loading?: boolean;
  skeletonHeight?: number;
  sx?: SxProps;
};

function InfoRowGroup({ children, loading = false, skeletonHeight = 24, sx = {} }: InfoRowGroupProps) {
  const [maxLabelWidth, setMaxLabelWidth] = useState<number>(0);
  const [measurementStage, setMeasurementStage] = useState<'measuring' | 'complete'>('measuring');
  const containerRef = useRef<HTMLDivElement>(null);
  const { locale } = useLocaleContext();

  const resetMeasurement = () => {
    setMeasurementStage('measuring');
    setMaxLabelWidth(0);
  };

  useLayoutEffect(() => {
    if (loading || !containerRef.current) return;

    if (measurementStage === 'measuring' || maxLabelWidth === 0) {
      const labelElements = containerRef.current.querySelectorAll('.info-row-label');

      if (labelElements.length > 0) {
        let maxWidth = 0;
        labelElements.forEach((label) => {
          const width = (label as HTMLElement).offsetWidth;
          if (width > maxWidth) {
            maxWidth = width;
          }
        });

        maxWidth += 16;

        if (maxWidth > 0) {
          setMaxLabelWidth(maxWidth);
          requestAnimationFrame(() => {
            setMeasurementStage('complete');
          });
        }
      }
    }
  }, [children, loading, measurementStage, locale]); // 添加locale作为依赖项

  useEffect(() => {
    resetMeasurement();
  }, [locale]);

  // Create skeleton rows for loading state
  const renderSkeletons = () => {
    // Count the number of InfoRow children
    let count = 0;
    Children.forEach(children, (child) => {
      if (isValidElement(child) && child.type && (child.type as any).displayName === 'InfoRow') {
        count++;
      }
    });

    return Array(count)
      .fill(0)
      .map((_, index) => (
        <Box key={`skeleton-row-${count - index}`} sx={{ display: 'flex', gap: 2 }}>
          <Skeleton width="30%" height={skeletonHeight} />
          <Skeleton width="65%" height={skeletonHeight} />
        </Box>
      ));
  };

  // Clone children with calculated width
  const renderChildren = () => {
    return Children.map(children, (child) => {
      if (isValidElement(child) && child.type && (child.type as any).displayName === 'InfoRow') {
        const childProps = {
          ...child.props,
          sx: {
            ...child.props.sx,
            visibility: measurementStage === 'measuring' ? 'hidden' : 'visible',
            '.info-row-label': {
              width: maxLabelWidth > 0 ? `${maxLabelWidth}px` : 'auto',
              minWidth: maxLabelWidth > 0 ? `${maxLabelWidth}px` : 'auto',
              whiteSpace: 'nowrap',
              transition: 'width 0.3s ease-out, min-width 0.3s ease-out',
            },
          },
        };
        return cloneElement(child as ReactElement<any>, childProps);
      }
      return child;
    });
  };

  return (
    <InfoRowGroupContext.Provider value>
      <Box ref={containerRef} sx={{ ...sx }}>
        {loading ? renderSkeletons() : renderChildren()}
      </Box>
    </InfoRowGroupContext.Provider>
  );
}

export default InfoRowGroup;
