"use client";

import { useLocale } from "next-intl";
import dynamic from "next/dynamic";
import { useEffect, useState } from "react";
import "keen-slider/keen-slider.min.css";
import { useKeenSlider } from "keen-slider/react";

// This code helps load ApexCharts for browser only
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });

export default function Charts({ graphs }: { graphs: any[] }) {
  const [loading, setLoading] = useState(true);
  const [currentSlide, setCurrentSlide] = useState(0);
  const [loaded, setLoaded] = useState(false);
  const [myGraphs, setMyGraphs] = useState<any[]>([]);
  const locale = useLocale();
  const [sliderRef, instanceRef] = useKeenSlider<HTMLDivElement>({
    initial: 0,

    slideChanged(slider: any) {
      setCurrentSlide(slider.track.details.rel);
    },
    created() {
      setLoaded(true);
    },
  });

  useEffect(() => {
    setLoading(false);
  }, []);

  useEffect(() => {
    if (!loading && instanceRef.current) {
      instanceRef.current.update();
    }
  }, [loading, instanceRef]);
  useEffect(() => {
    graphs.map((graph) => {
      setMyGraphs((graphs) => [
        ...graphs,
        {
          options: {
            chart: {
              id: graph.title[locale],
            },
            xaxis: {
              categories: [
                ...graph.record.map((record: any) => parseInt(record.year)),
              ],
            },
          },
          series: [
            {
              name: graph.title[locale],
              data: [
                ...graph.record.map((record: any) => parseInt(record.number)),
              ],
            },
          ],
        },
      ]);
    });
  }, [graphs]);

  return (
    <div className="relative lg:px-24">
      <div ref={sliderRef} className="keen-slider">
        {myGraphs &&
          loaded &&
          myGraphs.map((graph, i) => (
            <div className={`keen-slider__slide`} key={i}>
              <div className="mixed-chart">
                <Chart
                  options={graph.options}
                  series={graph.series}
                  type="bar"
                  width="100%"
                />
              </div>
              <h4 className="text-center">{graph?.options?.chart?.id}</h4>
            </div>
          ))}
      </div>
      {loaded && instanceRef.current && (
        <>
          <Arrow
            left
            onClick={(e: any) =>
              e.stopPropagation() || instanceRef?.current?.prev()
            }
            disabled={currentSlide === 0}
          />

          <Arrow
            onClick={(e: any) =>
              e.stopPropagation() || instanceRef?.current?.next()
            }
            disabled={
              currentSlide ===
              instanceRef.current.track.details?.slides.length - 1
            }
          />
        </>
      )}
    </div>
  );
}

function Arrow(props: {
  disabled: boolean;
  left?: boolean;
  onClick: (e: any) => void;
}) {
  const disabled = props.disabled ? " arrow--disabled" : "";
  return (
    <svg
      onClick={props.onClick}
      className={`arrow ${
        props.left ? "arrow--left" : "arrow--right"
      } ${disabled}`}
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
    >
      {props.left && (
        <path d="M16.67 0l2.83 2.829-9.339 9.175 9.339 9.167-2.83 2.829-12.17-11.996z" />
      )}
      {!props.left && (
        <path d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z" />
      )}
    </svg>
  );
}
