import React, { useState, useRef } from "react";
import ReactEcharts from "echarts-for-react";
import { Grid } from "../grid/Grid";
import * as echarts from "echarts";

export const AdvancedChart = ({ info, title, seperator, type, group }) => {
  const [isGroup, setIsGroup] = useState(group);
  const chartRef = useRef(null);

  const PALETTE = [
    "#1105f5",
    "#f50505",
    "#f5056d",
    "#f505f5",
    "#05a5f5",
    "#05f5bd",
    "#05f57d",
    "#1f4f33",
    "#95DFD3",
    "#AEC7ED",
    "#92BFFF",
    "#B1B1E0",
    "#fdcb6e",
    "#636e72",
    "#d63031",
    "#7f8fa6",
    "#40739e",
  ];

  const colorByIndex = (i) => PALETTE[i % PALETTE.length];

  const createGradient = (startColor, endColor) => ({
    type: "linear",
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      { offset: 0, color: startColor },
      { offset: 1, color: endColor },
    ],
  });

  const onChartReady = (echart) => {
    chartRef.current = echart;
  };

  const handleGroupToggle = () => {
    setIsGroup((prev) => !prev);
    if (chartRef.current) {
      chartRef.current.setOption(getOption());
    }
  };

  const getOption = () => {
    if (type === "pie") {
      return {
        title: {
          text: title,
          textStyle: {
            fontWeight: "bold",
            fontSize: 16,
            fontFamily: "iranyekan",
          },
          left: "center",
          padding: 10,
        },
        tooltip: { trigger: "item", formatter: "{a} <br/>{b}: {c} ({d}%)" },
        legend: {
          orient: "vertical",
          right: 10,
          top: "center",
          data: info?.map((item) => item?.name),
          textStyle: {
            fontFamily: "iranyekan",
            width: 100,
            overflow: "truncate",
            ellipsis: "...",
          },
        },
        color: info?.map((_, i) => colorByIndex(i)),
        series: [
          {
            name: title,
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: { show: false, position: "center" },
            emphasis: {
              label: { show: true, fontSize: "18", fontWeight: "bold" },
            },
            labelLine: { show: false },
            data: info?.map((item, i) => ({
              value: item.data[0],
              name: item.name,
              itemStyle: {
                color: colorByIndex(i),
              },
            })),
          },
        ],
        textStyle: { fontFamily: "iranyekan" },
      };
    }

    return {
      title: {
        text: title,
        textStyle: {
          fontWeight: "bold",
          fontSize: 16,
          fontFamily: "iranyekan",
        },
        left: "center",
        padding: 10,
      },
      xAxis: {
        type: "category",
        data: seperator,
        axisLabel: {
          rotate: 30,
          interval: 0,
          width: 60,
          overflow: "truncate",
          fontSize: 10,
        },
      },
      yAxis: isGroup
        ? [
            {
              type: "value",
              axisLabel: {
                formatter: function (a) {
                  a = +a;
                  return isFinite(a) ? echarts.format.addCommas(+a / 1000) : "";
                },
              },
            },
          ]
        : { type: "value" },
      dataZoom: [
        { show: false, start: 0, end: 100 },
        { type: "inside", start: 94, end: 100 },
      ],
      toolbox: {
        show: true,
        feature: {
          mark: {
            show: true,
            title: {
              mark: "علامت گذاری",
              markUndo: "حذف علامت",
              markClear: "پاک کردن همه علامت‌ها",
            },
          },
          magicType: {
            show: true,
            type: ["line", "bar"],
            title: { line: "خطی", bar: "میله‌ای", pie: "دایره ای" },
          },
          saveAsImage: { show: true, title: "ذخیره به عنوان تصویر" },
          myCustomButton: {
            show: true,
            title: isGroup ? "نمایش گروهی" : "نمایش جداگانه",
            icon: "path://M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",
            onclick: handleGroupToggle,
          },
        },
      },
      grid: { top: "20%", left: "1%", right: "1%", containLabel: true },
      textStyle: { fontFamily: "iranyekan" },

      color: info?.map((_, i) => colorByIndex(i)),

      series: info?.map((item, i) => {
        const base = colorByIndex(i);
        const next = colorByIndex(i + 1);
        return {
          ...item,
          smooth: true,
          type,
          itemStyle: {
            color: base,
          },
          areaStyle: {
            color: createGradient(base, next),
          },
          emphasis: { focus: "series" },
          stack: isGroup ? false : "stack",
        };
      }),
      tooltip: { trigger: "axis", axisPointer: { type: "cross" } },
      legend: {
        data: info?.map((item) => item?.name),
        itemGap: 10,
        top: "10%",
        type: "scroll",
        padding: [5, 50],
        textStyle: { width: 100, overflow: "truncate", ellipsis: "..." },
      },
    };
  };

  return (
    <Grid xs={12} style={{ height: "100%" }}>
      <ReactEcharts
        option={getOption()}
        style={{ height: "100%", width: "100%" }}
        onChartReady={onChartReady}
      />
    </Grid>
  );
};
