"use client";

import dynamic from "next/dynamic";
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });
import { useTheme } from "@mui/material/styles";
import ParentCard from "@/app/components/shared/ParentCard";
import React, { useMemo } from "react";
import { ApexOptions } from "apexcharts";
import { Typography, Grid, Box, Button } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import dayjs, { Dayjs } from "dayjs";

const ApexArea = ({
  graphData,
  startDate,
  endDate,
  setStartDate,
  setEndDate,
  onUpdate,
  isLoading,
}: {
  graphData?: { labels: string[]; values: number[] };
  startDate: Dayjs;
  endDate: Dayjs;
  setStartDate: (d: Dayjs) => void;
  setEndDate: (d: Dayjs) => void;
  onUpdate: () => void;
  isLoading: boolean;
}) => {
  const theme = useTheme();
  const primary = theme.palette.primary.main;

  const { safeLabels, safeValues } = useMemo(() => {
    return {
      safeLabels: Array.isArray(graphData?.labels) ? graphData!.labels : [],
      safeValues: Array.isArray(graphData?.values)
        ? graphData!.values.map((v: any) => Number(v))
        : [],
    };
  }, [graphData]);

  const options: ApexOptions = useMemo(() => {
    return {
      chart: {
        id: "area-chart",
        fontFamily: "inherit",
        foreColor: "#adb0bb",
        toolbar: { show: false },
      },
      dataLabels: { enabled: false },
      stroke: { width: 3, curve: "smooth" },
      colors: [primary],
      xaxis: {
        categories: safeLabels,
        type: "category",
        title: { text: "Date" },
        labels: { rotate: -45 },
      },
      yaxis: {
        labels: { show: true },
        title: { text: "Deposits ($)" },
      },
      legend: {
        show: true,
        position: "bottom",
      },
      grid: { show: false },
      tooltip: {
        theme: "dark",
        fillSeriesColor: false,
        y: {
          formatter: (val: number) => `$${val}`,
        },
      },
    };
  }, [safeLabels, primary]);

  const series = useMemo(() => {
    return [
      {
        name: "Deposits",
        data: safeValues,
      },
    ];
  }, [safeValues]);

  return (
    <Grid size={12}>
      <ParentCard
        title={
          <Box display="flex" alignItems="center" justifyContent="space-between" width="100%">
            <Typography variant="h6">Day-wise Deposits</Typography>
            <Box display="flex" gap={2} alignItems="center">
              <DatePicker
                value={startDate}
                onChange={(newVal) => newVal && setStartDate(newVal)}
                format="YYYY-MM-DD"
              />
              <DatePicker
                value={endDate}
                onChange={(newVal) => newVal && setEndDate(newVal)}
                format="YYYY-MM-DD"
              />
              <Button variant="contained" onClick={onUpdate} disabled={isLoading}>
                {isLoading ? "Loading..." : "Update"}
              </Button>
            </Box>
          </Box>
        }
      >
        {safeLabels.length > 0 && safeValues.length > 0 ? (
          <Chart options={options} series={series} type="area" height="300px" width="100%" />
        ) : (
          <Typography variant="body2" sx={{ textAlign: "center", mt: 5 }}>
            No deposit data available
          </Typography>
        )}
      </ParentCard>
    </Grid>
  );
};

export default ApexArea;
