import Chart, { useChart } from '@/shared/components/chart';

// ----------------------------------------------------------------------

type Props = {
  series: {
    name: string;
    data: number[];
    axis: string[],
    color: string
  }[];
  searchValue: string;
};

export default function AnalyticsTasksProgress({ series, searchValue }: Props) {
  // Vérifier si la recherche est vide
  if (searchValue.trim() == "") {
    // Si la recherche est vide, afficher toutes les séries de données
    const chartOptions = useChart({
      plotOptions: {
        bar: {
          columnWidth: '16%',
        },
      },
      stroke: {
        show: false,
      },
      xaxis: {
        categories: series.length > 0 ? series[0].axis : [],
      },
      tooltip: {
        y: {
          formatter: (value: number) => `${value} `,
        },
      },
    });

    return (
      <Chart dir="ltr" type="bar" series={series} options={chartOptions} width="100%" height={320} />
    );
  }

  const filteredSeries = series.map((item) => {
    const filteredAxis = item.axis.filter((axisItem) =>
      axisItem.toLowerCase().includes(searchValue.toLowerCase())
    );
    const filteredData = filteredAxis.map((axisItem) => {
      const index = item.axis.indexOf(axisItem);
      return item.data[index];
    });
    return {
      ...item,
      axis: filteredAxis,
      data: filteredData,
    };
  }).filter((item) => item.axis.length > 0);


  if (filteredSeries.length === 0) {
    return null;
  }

  const chartOptions = useChart({
    plotOptions: {
      bar: {
        columnWidth: '16%',
      },
    },
    stroke: {
      show: false,
    },
    xaxis: {
      categories: filteredSeries[0].axis,
    },
    tooltip: {
      y: {
        formatter: (value: number) => `${value} `,
      },
    },
  });

  return (
    <Chart dir="ltr" type="bar" series={filteredSeries} options={chartOptions} width="100%" height={500} />
  );
}