"use client";
import getData from "@/utils/fetch";
import { useQuery } from "@tanstack/react-query";
import { useThemeMode } from "flowbite-react";
import dynamic from "next/dynamic";
import { FC, useEffect, useState } from "react";
import { toast } from "react-toastify";
import Spinner from "../spinner";
import FilterForm from "../common/filter-form";
import { Filter } from "../forms/schema/filter";
import GraphChartSkeleton from "./graph-skeleton-loader";
const ApexChart = dynamic(() => import("react-apexcharts"), { ssr: false });
export const invoiceFilter: Filter[] = [
  {
    name: "year_filter",
    type: "dropdown",
    placeholder: `${new Date().getFullYear()}`,
    idName: "year_filter",
    initialData: [
      { name: new Date().getFullYear(), id: new Date().getFullYear() },
      { name: new Date().getFullYear() - 1, id: new Date().getFullYear() - 1 },
      { name: new Date().getFullYear() - 2, id: new Date().getFullYear() - 2 },
      { name: new Date().getFullYear() - 3, id: new Date().getFullYear() - 3 },
      { name: new Date().getFullYear() - 4, id: new Date().getFullYear() - 4 },
    ],
  },
];

export interface GraphSeries {
  name: string;
  data: number[];
  color: string;
}
export interface ChartData {
  months: string[];
  series: GraphSeries[];
}
export interface GraphData {
  graphData: ChartData;
  isLoading?: boolean;
  filterValue?: string;
  setFilter?: (x: string) => void;
}

const GraphChart: FC = () => {
  const [filterValue, setFilter] = useState(null);
  let url = `/api/v1/dashboard-graph-chart`;
  if (filterValue) {
    url = `${url}?${filterValue}`
  }
  const getClientCount = async () => {
    const data = await getData(url);

    if (!data?.success) {
      return toast.error(data);
    }
    return data?.data;
  };
  const { data: graph, isLoading, refetch } = useQuery<any>({
    queryKey: ["graph-chart"],
    queryFn: () => getClientCount(),
    retry: 0,
  });
  console.log(graph);

  useEffect(() => {
    if (!filterValue?.includes("#")) {
      refetch();
    }
  }, [filterValue]);

  return (
    <>
      <div className="mt-5">
        <InvoiceMonth graphData={graph} isLoading={isLoading} setFilter={setFilter} />
      </div>
    </>
  );
};
const InvoiceAndExpenseChart: FC<GraphData> = function ({ graphData, setFilter }) {
  const { mode } = useThemeMode();
  const isDarkTheme = mode === "dark";

  const borderColor = isDarkTheme ? "#374151" : "#F3F4F6";
  const labelColor = isDarkTheme ? "#9ca3af" : "#6B7280";
  const opacityFrom = isDarkTheme ? 0 : 0.45;
  const opacityTo = isDarkTheme ? 0.15 : 0;

  const options: ApexCharts.ApexOptions = {
    stroke: {
      curve: "smooth",
    },
    chart: {
      type: "area",
      fontFamily: "Inter, sans-serif",
      foreColor: labelColor,
      toolbar: {
        show: false,
      },
    },
    fill: {
      type: "gradient",
      gradient: {
        opacityFrom,
        opacityTo,
        type: "vertical",
      },
    },
    dataLabels: {
      enabled: false,
    },
    tooltip: {
      style: {
        fontSize: "14px",
        fontFamily: "Inter, sans-serif",
      },
    },
    grid: {
      show: true,
      borderColor: borderColor,
      strokeDashArray: 1,
      padding: {
        left: 35,
        bottom: 15,
      },
    },
    markers: {
      size: 5,
      strokeColors: "#ffffff",
      hover: {
        size: undefined,
        sizeOffset: 3,
      },
    },
    xaxis: {
      categories: graphData?.months,
      labels: {
        style: {
          colors: [labelColor],
          fontSize: "14px",
          fontWeight: 500,
        },
      },
      axisBorder: {
        color: borderColor,
      },
      axisTicks: {
        color: borderColor,
      },
      crosshairs: {
        show: true,
        position: "back",
        stroke: {
          color: borderColor,
          width: 1,
          dashArray: 10,
        },
      },
    },
    yaxis: {
      labels: {
        style: {
          colors: [labelColor],
          fontSize: "14px",
          fontWeight: 500,
        },
        formatter: function (value) {
          return `৳ ` + value;
        },
      },
    },
    legend: {
      fontSize: "14px",
      fontWeight: 500,
      fontFamily: "Inter, sans-serif",
      labels: {
        colors: [labelColor],
      },
      itemMargin: {
        horizontal: 10,
      },
    },
    responsive: [
      {
        breakpoint: 1024,
        options: {
          xaxis: {
            labels: {
              show: false,
            },
          },
        },
      },
    ],
  };
  const series = graphData?.series;

  return (
    <>
      <div className="-mt-4 font-normal text-base w-full flex justify-end">
        <div className="max-w-[300px] w-full">
          <FilterForm schema={invoiceFilter} grids={1} setFilter={setFilter} searchButton={false} />
        </div>
      </div>
      <ApexChart height={420} options={options} series={series} type="area" />
    </>
  );
};

const InvoiceMonth: FC<GraphData> = function ({ graphData, isLoading, setFilter }) {
  return (
    <div className="rounded-lg bg-white p-4 shadow sm:p-6 xl:p-8 dark:bg-gray-800">
      {isLoading && <GraphChartSkeleton />}
      {!isLoading && <InvoiceAndExpenseChart graphData={graphData} setFilter={setFilter} />}
    </div>
  );
};
export default GraphChart;
