"use client";
import { useEffect, useState } from "react";
import ReactApexChart from "react-apexcharts";
import dummy from "../../../../const/dummy.json";
import { getStatisticUsersMonthly } from "@/services/article";

function getRangeAcrossMonths(
  data: any[],
  startMonth: number,
  startDay: number,
  endMonth: number,
  endDay: number
) {
  const labels: string[] = [];
  const users: { name: string; data: number[] }[] = [];
  const sortedData = data.sort((a, b) => a.month - b.month);
  console.log("sorted,data", sortedData);
  for (const monthData of sortedData) {
    const { month, users: u } = monthData;
    if (month < startMonth || month > endMonth) continue;
    console.log("uuu", month, startMonth, endMonth, u.length);

    let startIndex = 0;
    let endIndex = u[0].data.length - 1;

    if (month === startMonth) startIndex = startDay - 1;
    if (month === endMonth) endIndex = endDay - 1;

    console.log("start,eend", startIndex, endIndex, month);
    for (let j = 0; j < u.length; j++) {
      const now = u[j].data;
      //   console.log("u.j", now);
      const temp = [];
      for (let i = startIndex; i <= endIndex; i++) {
        temp.push(now[i]);

        if (j == 0) {
          const label = `${(i + 1).toString().padStart(2, "0")} - ${month
            .toString()
            .padStart(2, "0")}`;

          labels.push(label);
        }
      }
      const existing = users.find((item) => item.name === u[j].name);
      if (existing) {
        existing.data.push(...temp); // gabungkan data
      } else {
        users.push({ name: u[j].name, data: temp }); // tambahkan baru
      }
    }
  }

  console.log("users", users);

  return { users, labels };
}

const ApexMultiLineChart = (props: {
  type: string;
  date: string;
  range: { start: any; end: any };
}) => {
  const { date, type, range } = props;
  const [datas, setDatas] = useState<any>([]);
  const [years, setYear] = useState("");

  const [series, setSeries] = useState<any>([]);
  const [categories, setCategories] = useState<string[]>([]);

  useEffect(() => {
    initFetch();
    console.log("type", type);
  }, [date, type, range.start, range.end]);

  const initFetch = async () => {
    const splitDate = date.split(" ");
    const splitDateDaily = String(range.start.year);
    console.log("split", splitDate);
    console.log("daily", splitDateDaily);
    let data: any = [];

    if (
      (type === "monthly" && splitDate[1] === years) ||
      (type === "daily" && splitDateDaily === years)
    ) {
      data = datas;
    } else {
      const res = await getStatisticUsersMonthly(
        type === "monthly" ? splitDate[1] : splitDateDaily
      );
      console.log("fetch", res?.data?.data);
      data = res?.data?.data;
      data = dummy.data;
      setDatas(data);
    }

    if (type === "daily") {
      console.log(
        "aaa",
        range.start.month,
        range.start.day,
        range.end.month,
        range.end.day
      );
      const mappedData = getRangeAcrossMonths(
        data,
        range.start.month,
        range.start.day,
        range.end.month,
        range.end.day
      );
      setSeries(mappedData.users);
      setCategories(mappedData.labels);
    }

    if (type === "monthly") {
      console.log("daaa", data);
      const getDatas = data?.find(
        (a: any) =>
          a.month == Number(splitDate[0]) && a.year === Number(splitDate[1])
      );
      if (getDatas) {
        console.log("datanya", getDatas.users);
        setSeries(getDatas.users);
      } else {
        setSeries([]);
      }
    }

    setYear(type === "monthly" ? splitDate[1] : splitDateDaily);
  };
  return (
    <div>
      <div id="chart">
        <ReactApexChart
          series={series}
          options={{
            chart: {
              height: 600,
              type: "line",
              dropShadow: {
                enabled: true,
                color: "#000",
                top: 18,
                left: 7,
                blur: 10,
                opacity: 0.5,
              },
              zoom: {
                enabled: true,
              },
              toolbar: {
                show: false,
              },
            },
            colors: [
              "#1f77b4",
              "#2ca02c",
              "#9467bd",
              "#8c564b",
              "#e377c2",
              "#7f7f7f",
              "#bcbd22",
              "#17becf",
              "#aec7e8",
              "#98df8a",
              "#c5b0d5",
              "#c49c94",
              "#9edae5",
              "#393b79",
              "#637939",
              "#8c6d31",
              "#843c39",
              "#7b4173",
              "#3182bd",
              "#6baed6",
              "#9ecae1",
              "#31a354",
              "#74c476",
              "#a1d99b",
              "#756bb1",
              "#9e9ac8",
              "#bcbddc",
              "#636363",
              "#969696",
              "#bdbdbd",
              "#17becf",
              "#8da0cb",
              "#66c2a5",
              "#a6d854",
              "#ffd92f",
              "#b3b3b3",
              "#80b1d3",
              "#fdb462",
            ],
            dataLabels: {
              enabled: true,
            },
            stroke: {
              curve: "smooth",
            },
            title: {
              text: "Users",
              align: "left",
            },
            grid: {
              borderColor: "#e7e7e7",
              row: {
                colors: ["#f3f3f3", "transparent"],
                opacity: 0.5,
              },
            },
            markers: {
              size: 0.5,
            },
            xaxis: {
              categories: type == "daily" ? categories : [],

              title: {
                text: "Days",
              },
            },
            yaxis: {
              title: {
                text: "Articles",
              },
              min: 0,
              max: 50,
            },
            legend: {
              position: "right",
              horizontalAlign: "right",
              floating: false,
              offsetY: -25,
              offsetX: -5,
            },
          }}
          type="line"
          height={600}
        />
      </div>
      <div id="html-dist"></div>
    </div>
  );
};

export default ApexMultiLineChart;
