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

type Props = {
  series: {
    name: string;
    data: number[];
    axis: string[];
    color: string;
  }[];
  searchValue: string; // Ensure this is provided
};

export default function ChartColumnSingle({ series, searchValue }: Props) {
  // Ensure searchValue is always a string
  const normalizedSearchValue = searchValue?.trim().toLowerCase() || '';

  if (normalizedSearchValue === '') {
    // Render full series when no search value
    const chartOptions = useChart({
      plotOptions: {
        bar: {
          columnWidth: '30%',
        },
      },
      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} />
    );
  }

  // Filter data based on searchValue
  const filteredSeries = series
    .map((item) => {
      const filteredAxis = item.axis.filter((axisItem) =>
        axisItem.toLowerCase().includes(normalizedSearchValue)
      );
      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; // No data to display
  }

  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={320} />
  );
}