import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Box, Heading, useColorMode, useMediaQuery } from "@chakra-ui/react";
import ChartsTabs from "../ChartsTabs";
import dayjs from "dayjs";
import { useGetDailyDataQuery, useGetDateWiseDataQuery, useGetMonthlyDataQuery } from "../../Services/api.service";
import { timeZone } from "../../Constants/Constants";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

const LineChart = () => {
  const { colorMode } = useColorMode();
  const [selectedValue, setSelectedValue] = useState("12 Months");
  const [labels, setLabels] = useState([]);
  const [dataset, setDataset] = useState([]);
  const [isMobile] = useMediaQuery("(max-width: 768px)");

  const {
    data: monthlyData,
    isLoading: monthlyDataLoading,
  } = useGetMonthlyDataQuery(timeZone === "Asia/Calcutta" ? "Asia/Kolkata" : timeZone);// Check if the screen is desktop or mobile

  const isDesktop = window.innerWidth >= 768;
  
  // Monthly dataset
  const dataSetMonthly = monthlyData?.map((data) => data?.transactionCount);
  
  // Full labels for desktop: "Month YYYY"
  const fullMonthLabels = monthlyData?.map((data) => `${data?.monthName} `);
  
  // Short labels for mobile: "Mon 'YY"
  const shortMonthLabels = monthlyData?.map((data) => `${data?.monthName.slice(0, 3)} ${data?.year.toString().slice(-2)}`);
  
  
  

  const {
    data: dailyData,
    isLoading: dailyDataLoading,
  } = useGetDailyDataQuery(timeZone === "Asia/Calcutta" ? "Asia/Kolkata" : timeZone);

  const dataSetDaily = dailyData?.map((data) => data?.transactionCount);
  const dataLableDaily = dailyData?.map((data) => data?.hour);

  const {
    data: dateData,
    isLoading: dateDataLoading,
  } = useGetDateWiseDataQuery(timeZone === "Asia/Calcutta" ? "Asia/Kolkata" : timeZone);

  const dataSetDate = dateData?.data?.map((data) => data?.transactionCount);
  const dataLableDate = dateData?.data?.map((data) => data?.dayName);

  useEffect(() => {
    if (selectedValue === "24 Hrs") {
      setLabels(dataLableDaily);
      setDataset(dataSetDaily);
    } else if (selectedValue === "30 Days") {
      setLabels(dataLableDate);
      setDataset(dataSetDate);
    } else if (selectedValue === "12 Months") {
      setLabels(isMobile ? shortMonthLabels : fullMonthLabels);
      setDataset(dataSetMonthly);
    }
  }, [selectedValue, dailyData, dateData, monthlyData, isMobile]);

  const data = {
    labels: labels,
    datasets: [
      {
        label: "Transaction Data",
        data: dataset,
        borderColor: "#978FED",
        tension: 0.3,
        pointRadius: 4,
        pointBackgroundColor: colorMode === "light" ? "#fff" : "#232127",
        pointBorderColor: "#978FED",
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "#978FED",
        borderWidth: 2,
        pointBorder: 0,
      },
    ],
  };
  // Calculate maximum value with a 10% buffer and round it up to the nearest whole number
  // console.log(dataset);
  // const maxYValue = Math.round(Math.max(...dataset) * 1.1);
  
  
  // const maxYValue = Math?.ceil(Math?.max(...dataset) * 1.1);

  const options = {
    responsive: true,
    plugins: {
      legend: { display: false },
      tooltip: {
        callbacks: {
          title: (tooltipItems) => {
            const index = tooltipItems[0]?.dataIndex;
            let data;
            if (selectedValue === "24 Hrs") {
              data = dailyData[index];
            } else if (selectedValue === "30 Days") {
              data = dateData?.data[index];
            } else if (selectedValue === "12 Months") {
              data = monthlyData[index];
            }
            return data?.dayName || data?.monthName || '';
          },
          beforeLabel: (tooltipItem) => {
            const index = tooltipItem.dataIndex;
            let data;
            if (selectedValue === "24 Hrs") {
              data = dailyData[index];
            } else if (selectedValue === "30 Days") {
              data = dateData?.data[index];
            } else if (selectedValue === "12 Months") {
              data = monthlyData[index];
            }
            return `Transactions: ${data?.transactionCount}`;
          },
          label: (tooltipItem) => {
            const index = tooltipItem.dataIndex;
            let data;
            if (selectedValue === "24 Hrs") {
              data = dailyData[index];
            } else if (selectedValue === "30 Days") {
              data = dateData?.data[index];
            } else if (selectedValue === "12 Months") {
              data = monthlyData[index];
            }
            return `Price: $${data?.totalPrice}`;
          },
          afterLabel: (tooltipItem) => {
            const index = tooltipItem.dataIndex;
            let data;
            if (selectedValue === "24 Hrs") {
              data = dailyData[index];
            } else if (selectedValue === "30 Days") {
              data = dateData?.data[index];
            } else if (selectedValue === "12 Months") {
              data = monthlyData[index];
            }
            return `Gas Fee: ${data?.totalGasFee}`;
          },
        },
        backgroundColor: "#fff",
        titleColor: "#4B4B4B",
        bodyColor: "#4B4B4B",
        displayColors: false,
        padding: 12,
        bodyFont: {
          size: 14,
          lineHeight: 1.3,
        },
        boxShadow: "0px 4px 12px rgba(0, 0, 0, 0.1)",
        borderColor: "#ccc",
        borderWidth: 1,
      },
    },
    scales: {
      y: {
        // max: maxYValue, // Dynamically set max value
        beginAtZero: true,
        ticks: {
          callback: (value) => value / 1000 + "k",
        },
        grid: {
          border: false,
          borderColor: "transparent",
        },
      },
      x: {
        grid: {
          border: false,
          borderColor: "transparent",
        },
      },
    },
  };

  return (
    <>
      <Box
        display={{ base: "block", md: "flex" }}
        justifyContent={"space-between"}
        alignItems={"center"}
        mb={{ base: 4, md: 4 }}
      >
        <Heading
          mt={{ base: 2, md: 0 }}
          fontSize={{ base: "sm", md: "md" }}
          fontWeight={500}
          mb={{ base: "5px", md: "0px" }}
          px={{ base: "8px", md: "0px" }}
        >
          Transaction History
        </Heading>
        <ChartsTabs
          setSelectedValue={setSelectedValue}
          selectedValue={selectedValue}
          days={dayjs().daysInMonth()}
        />
      </Box>
      <Line data={data} options={options} />
    </>
  );
};

export default LineChart;
