import apiFetch from "@/lib/apiFetch";
import { Card, Divider, Flex, Stack, Text, Title } from "@mantine/core";
import { IconChartBar } from "@tabler/icons-react";
import type { EChartsOption } from "echarts";
import EChartsReact from "echarts-for-react";
import { useEffect, useState } from "react";
import useSWR from "swr";

export default function DashboardGrafik() {
   const [options, setOptions] = useState<EChartsOption>({});
   const { data, mutate, isLoading } = useSWR(
      "grafik-dashboard",
      async () => {
         return apiFetch.api.dashboard.grafik.get().then(res => res.data);
      }
   );

   const loadData = () => {
      if (!data) return;
      const option: EChartsOption = {
         darkMode: true,
         animation: true,
         legend: {
            textStyle: { color: "#fff" }
         },
         tooltip: {},
         dataset: {
            dimensions: data.dimensions,
            source: data.source
         },
         xAxis: {
            type: "category",
            axisLabel: { color: "#fff" }
         },
         yAxis: {
            type: "value",
            minInterval: 1,
            axisLabel: { color: "#fff" }
         },
         color: ["#1abc9c", "#10816aff"],
         series: [
            { type: "bar" },
            { type: "bar" }
         ]
      };

      setOptions(option);
   };

   useEffect(() => {
      if (data) loadData();
   }, [data]);

   return (
      <Card
         radius="lg"
         p="xl"
         withBorder
         style={{
            background:
               "linear-gradient(145deg, rgba(25,25,25,0.95), rgba(45,45,45,0.85))",
            borderColor: "rgba(100,100,100,0.2)",
            boxShadow: "0 0 25px rgba(0,255,200,0.08)",
         }}
      >
         <Stack gap="sm">
            <Flex align="center" justify="space-between">
               <Flex direction={"column"}>
                  <Title order={4} c="gray.0">
                     Grafik Pengaduan dan Pelayanan Surat
                  </Title>
                  <Text size="sm">7 Hari Terakhir</Text>
               </Flex>
               <IconChartBar size={20} color="gray" />
            </Flex>
            <Divider my="xs" />
            <Stack gap="sm">
               <EChartsReact style={{ height: 400 }} option={options} />
            </Stack>
         </Stack>
      </Card>
   )
}