import BreakdownChart from '@composed-components/charts/BreakdownChart';
import { Stack, type SxProps } from '@mui/material';
import { has } from 'lodash';

import BreakdownSkeleton from './skeleton';
import { type BreakdownItemWithColor, type BreakdownProps } from './types';

const Breakdown = ({
  items = [],
  sx = {},
  slotProps = {},
  loading = false,
}: BreakdownProps) => {
  if (loading) {
    return <BreakdownSkeleton {...slotProps.skeleton} />;
  }

  const hasColors = items.every(item => has(item, 'color'));

  const values = items.map(item => item.value);
  const labels = items.map(item => item.label);
  const colors = hasColors
    ? items.map(item => (item as BreakdownItemWithColor).color)
    : undefined;

  return (
    <Stack
      className="Breakdown-root"
      {...slotProps.root}
      sx={
        {
          alignItems: 'center',
          gap: 2,
          ...sx,
          ...slotProps.root?.sx,
        } as SxProps
      }
    >
      <BreakdownChart
        values={values}
        colors={colors}
        labels={labels}
        {...slotProps.chart}
      />
    </Stack>
  );
};

export default Breakdown;
