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

import PieSkeleton from './skeleton';
import { type PieItemWithColor, type PieProps } from './types';

const Pie = ({
  copetin,
  title,
  description,
  items = [],
  sx = {},
  slotProps = {},
  legend = 'none',
  loading = false,
}: PieProps) => {
  if (loading) {
    return (
      <PieSkeleton
        copetin={copetin}
        title={title}
        description={description}
        legend={legend}
        {...slotProps.skeleton}
      />
    );
  }

  const showTitle = copetin || title || description;
  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 PieItemWithColor).color)
    : undefined;

  return (
    <Stack
      className="Pie-root"
      {...slotProps.root}
      sx={
        {
          alignItems: 'center',
          gap: 2,
          ...sx,
          ...slotProps.root?.sx,
        } as SxProps
      }
    >
      <PieChart
        values={values}
        colors={colors}
        labels={labels}
        legend={legend}
        {...slotProps.chart}
      />
      {showTitle && (
        <Title
          variant="M"
          copetin={copetin}
          title={title}
          description={description}
          centered
          {...slotProps.title}
        />
      )}
    </Stack>
  );
};

export default Pie;
