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

const styles = {
  container: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'column',
    gap: ({ spacing }) => spacing(1),
    height: ({ spacing }) => spacing(38),
  },
  grid: {
    display: 'flex',
    alignItems: 'flex-end',
    flex: '1 1 auto',
    gap: 0.5,
    width: '100%',
  },
  legend: {
    display: 'flex',
    alignItems: 'center',
    gap: ({ spacing }) => spacing(2),
    height: ({ spacing }) => spacing(5),
  },
  legendItem: {
    display: 'flex',
    alignItems: 'center',
    gap: ({ spacing }) => spacing(1.5),
  },
} satisfies Record<string, SxProps<Theme>>

const barSx = (height: number): SxProps<Theme> => ({
  flex: 1,
  height: `${height}%`,
  minWidth: 8,
})

export interface HistogramSkeletonProps {
  bins?: number
}

/**
 * Loading state for the Histogram widget. Mirrors Bar's skeleton structure
 * — a grid of bars (bin-shaped silhouette, anchored to the bottom) plus a
 * legend stub — so the placeholder reads consistently with Bar.
 */
export function HistogramSkeleton({ bins = 12 }: HistogramSkeletonProps) {
  // Sample heights mimicking a typical bell-shaped distribution.
  const heights = Array.from({ length: bins }, (_, i) => {
    const t = i / Math.max(1, bins - 1)
    return Math.round(20 + 80 * Math.exp(-((t - 0.5) ** 2) * 8))
  })
  return (
    <Box sx={styles.container}>
      <Box sx={styles.grid}>
        {heights.map((h, i) => (
          <Skeleton key={`bar-${i}`} variant='rectangular' sx={barSx(h)} />
        ))}
      </Box>
      <Box sx={styles.legend}>
        {[0, 1].map((i) => (
          <Box key={`legend-${i}`} sx={styles.legendItem}>
            <Skeleton variant='circular' width={8} height={8} />
            <Skeleton width={48} height={8} />
          </Box>
        ))}
      </Box>
    </Box>
  )
}
