'use client';

import * as React from 'react';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import CardHeader from '@mui/material/CardHeader';
import Divider from '@mui/material/Divider';
import { alpha, useTheme } from '@mui/material/styles';
import type { SxProps } from '@mui/material/styles';
import { ArrowClockwise as ArrowClockwiseIcon } from '@phosphor-icons/react/dist/ssr/ArrowClockwise';
import { ArrowRight as ArrowRightIcon } from '@phosphor-icons/react/dist/ssr/ArrowRight';
import type { ApexOptions } from 'apexcharts';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import dayjs, { Dayjs } from 'dayjs'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';

import { Chart } from '@/components/core/chart';
import { Box } from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';

export interface SalesProps {
  chartSeries: { name: string; data: number[] }[];
  sx?: SxProps;
  selectedDate: Dayjs;
  onYearChange: (any: any) => void;
  loading: boolean,
  title: string
}

export function AreaChart({ chartSeries, sx, selectedDate, onYearChange, loading, title }: SalesProps): React.JSX.Element {
  const chartOptions = useChartOptions();
  const safeChartSeries = chartSeries.map((series) => ({
    ...series,
    data: Array.from({ length: 12 }, (_, index) => {
      const value = Array.isArray(series.data) ? series.data[index] : 0;
      const parsed = Number(value ?? 0);
      return Number.isFinite(parsed) ? parsed : 0;
    }),
  }));

  const handleYearChange = (date: Dayjs | null) => {
    onYearChange(dayjs(date))
  }

  return (
    <Card sx={{ ...sx, position: 'relative', minHeight: 280 }}>
      {loading && <AppLoader fill size="md" />}
      <CardHeader
      sx={{flexDirection:{sm:'row',flexWrap:'wrap', gap:'20px', justifyContent:{sm:'space-between', xs:'center'}, alignItems:'center'}}}
        action={
          <LocalizationProvider dateAdapter={AdapterDayjs}>

            <DatePicker
              views={['year']}
              label="Select Year"
              value={dayjs(selectedDate)}
              onChange={(date) => handleYearChange(date)}
            />
          </LocalizationProvider>
        }
        title={title}
      />
      <CardContent>
        <Chart height={200} options={chartOptions} series={safeChartSeries} type="area" width="100%" />
      </CardContent>
      {/* <Divider />
      <CardActions sx={{ justifyContent: 'flex-end' }}>
        <Button color="inherit" endIcon={<ArrowRightIcon fontSize="var(--icon-fontSize-md)" />} size="small">
          Overview
        </Button>
      </CardActions> */}
    </Card>
  );
}

function useChartOptions(): ApexOptions {
  const theme = useTheme();

  return {
    chart: {
        height: 350,
        type: 'area',
        toolbar:{
            show:true,
            tools:{
                download:true,
                pan:false,
                reset:false,
                selection:false,
                zoom:false,
                zoomin:false,
                zoomout:false
            }

        }
      },
      colors: [theme.palette.primary.main, alpha(theme.palette.primary.main, 0.25)],
      dataLabels: {
        enabled: false
      },
      legend: { show: false },
      stroke: {
        curve: 'smooth' as const
      },
      xaxis: {
        type: 'category',
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
      },
      tooltip: {
        // shared: true,
        // intersect: false,
        hideEmptySeries: false,
        // x: {
        //   format: 'dd/MM/yy HH:mm'
        // },
        y: {
          formatter: function (value) {
            return value != null ? Number(value).toFixed(0) : '0';
          },
        },
      },
    // chart: { background: 'transparent', stacked: false, toolbar: { show: false } },
    // colors: [theme.palette.primary.main, alpha(theme.palette.primary.main, 0.25)],
    // dataLabels: { enabled: false },
    // fill: { opacity: 1, type: 'solid' },
    // grid: {
    //   borderColor: theme.palette.divider,
    //   strokeDashArray: 2,
    //   xaxis: { lines: { show: false } },
    //   yaxis: { lines: { show: true } },
    // },
    // legend: { show: false },
    // plotOptions: { bar: { columnWidth: '40px' } },
    // stroke: { colors: ['transparent'], show: true, width: 2 },
    // theme: { mode: theme.palette.mode },
    // xaxis: {
    //   axisBorder: { color: theme.palette.divider, show: true },
    //   axisTicks: { color: theme.palette.divider, show: true },
    //   categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    //   labels: { offsetY: 5, style: { colors: theme.palette.text.secondary } },
    // },
    // yaxis: {
    //   labels: {
    //     formatter: (value) => (value > 0 ? `${value}` : `${value}`),
    //     offsetX: -10,
    //     style: { colors: theme.palette.text.secondary },
    //   },
    // },
  };
}
