import {
  darken,
  lighten,
  Skeleton as MuiSkeleton,
  Stack,
  useTheme,
} from '@mui/material';

import { getBorderRadius } from '../../Skeleton/constants';
import AISpinner from '../AISpinner';

import {
  AI_ILLUMINATION_DURATION_S,
  aiIlluminationKeyframes,
} from './constants';
import { type AISkeletonProps } from './types';

const AISkeleton = ({
  isLoading = true,
  variant = 'rounded',
  sx,
  ...skeletonProps
}: AISkeletonProps) => {
  const theme = useTheme();

  if (!isLoading) return <>{skeletonProps.children}</>;

  const isLight = theme.palette.mode === 'light';
  const token = theme.palette.new.background.elements.grey;
  const baseColor = isLight ? darken(token, 0.15) : lighten(token, 0.08);
  const iconColor = theme.palette.new.text.neutral.inverted;
  const borderRadius = getBorderRadius(variant, theme);

  return (
    <Stack
      role="status"
      aria-label="Loading"
      sx={{
        position: 'relative',
        width: 'fit-content',
        overflow: 'hidden',
        borderRadius,
      }}
    >
      <MuiSkeleton
        animation={false}
        variant={variant}
        sx={{
          backgroundColor: baseColor,
          borderRadius,
          ...sx,
        }}
        {...skeletonProps}
      />
      <Stack
        aria-hidden
        sx={{
          position: 'absolute',
          inset: 0,
          pointerEvents: 'none',
          backgroundImage:
            'linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.6) 50%, transparent 100%)',
          animation: `${aiIlluminationKeyframes} ${AI_ILLUMINATION_DURATION_S}s ease-in-out infinite`,
          '@media (prefers-reduced-motion: reduce)': {
            animation: 'none',
          },
        }}
      />
      <Stack
        aria-hidden
        sx={{
          position: 'absolute',
          inset: 0,
          alignItems: 'center',
          justifyContent: 'center',
          pointerEvents: 'none',
        }}
      >
        <AISpinner color={iconColor} />
      </Stack>
    </Stack>
  );
};

export type { AISkeletonProps };

export default AISkeleton;
