import { Box, Skeleton } from '@mui/material'
import type { SxProps, Theme } from '@mui/material'
import type { CategorySize } from './types'

const styles = {
  root: {
    display: 'flex',
    flexDirection: 'column',
    gap: 1,
    py: 0.5,
  },
  // Mirror the real row layout: label + value on top, bar below.
  row: {
    display: 'flex',
    flexDirection: 'column',
    gap: 0.5,
  },
  rowHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    gap: 1,
  },
  // Small fixed-width shimmer pills — matches the visual density of the
  // real label / value cells without claiming the full row width.
  name: { height: 14, width: 80 },
  value: { height: 14, width: 48 },
} satisfies Record<string, SxProps<Theme>>

// Bar shimmer height matches the live bar track for each size variant so
// the skeleton doesn't visibly resize the row on data settle.
const BAR_HEIGHT: Record<CategorySize, number> = {
  small: 4,
  medium: 12,
}

// Varied widths give the bar shimmer a more realistic, less uniform feel.
// Cycles when `rows > WIDTH_PATTERNS.length`.
const WIDTH_PATTERNS = ['95%', '80%', '55%', '75%', '60%']

export interface CategorySkeletonProps {
  rows?: number
  /**
   * Visual density. Mirrors the live widget's `size` prop so the loading
   * shimmer's bar height matches what's about to render — no row jump
   * on data settle.
   */
  size?: CategorySize
}

export function CategorySkeleton({
  rows = 5,
  size = 'small',
}: CategorySkeletonProps) {
  return (
    <Box sx={styles.root}>
      {Array.from({ length: rows }).map((_, i) => (
        <Box key={`row-${i}`} sx={styles.row}>
          <Box sx={styles.rowHeader}>
            <Skeleton variant='rectangular' sx={styles.name} />
            <Skeleton variant='rectangular' sx={styles.value} />
          </Box>
          <Skeleton
            variant='rectangular'
            sx={{
              height: BAR_HEIGHT[size],
              width: WIDTH_PATTERNS[i % WIDTH_PATTERNS.length],
            }}
          />
        </Box>
      ))}
    </Box>
  )
}
