import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import Dropdown from '../../components/Dropdown';

import { IRootState } from '../../store';
import { getThemeChartColors, getThemeChartFont } from '../../lib/theme-colors';
import dynamic from 'next/dynamic';

const ReactApexChart = dynamic(() => import('react-apexcharts'), {
    ssr: false,
});
const RevenueDashboard = ({ setShowCart }: { setShowCart: any }) => {
    const [isMounted, setIsMounted] = useState(false);
    useEffect(() => {
        setIsMounted(true);
    }, []);
    const [filterRevenue, setFilterRevenue] = useState('yearly');

    const isDark = useSelector((state: IRootState) => state.themeConfig.theme === 'dark' || state.themeConfig.isDarkMode);
    const colorScheme = useSelector((state: IRootState) => state.themeConfig.colorScheme);
    const chartColors = getThemeChartColors(colorScheme);
    const [dataRevenue, setDataRevenue] = useState({
        totalRevenue: 0,
        currentData: [],
        lastData: [],
        label: [],
        name: '',
    });

    const fetchDataRevenue = async () => {
        const api_url = process.env.API_URL;
        const response = await fetch(`${api_url}api/dashboard/revenue?filter=${filterRevenue}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
        });
        const res = await response.json();
        setDataRevenue(res);
    };

    useEffect(() => {
        fetchDataRevenue();
    }, [filterRevenue]);

    //Revenue Chart
    const revenueChart: any = {
        series: [
            {
                name: `Current ${dataRevenue.name}`,
                data: dataRevenue.currentData,
            },
            {
                name: `Last ${dataRevenue.name}`,
                data: dataRevenue.lastData,
            },
        ],
        options: {
            chart: {
                height: 325,
                type: 'area',
                fontFamily: getThemeChartFont(colorScheme),
                zoom: {
                    enabled: false,
                },
                toolbar: {
                    show: false,
                },
            },

            dataLabels: {
                enabled: false,
            },
            stroke: {
                show: true,
                curve: 'smooth',
                width: 2,
                lineCap: 'square',
            },
            dropShadow: {
                enabled: true,
                opacity: 0.2,
                blur: 10,
                left: -7,
                top: 22,
            },
            colors: [chartColors[0], chartColors[4] || '#E7515A'],

            labels: dataRevenue.label,
            xaxis: {
                axisBorder: {
                    show: false,
                },
                axisTicks: {
                    show: false,
                },
                crosshairs: {
                    show: true,
                },
                labels: {
                    offsetX: 0,
                    offsetY: 5,
                    style: {
                        fontSize: '12px',
                        cssClass: 'apexcharts-xaxis-title',
                    },
                },
            },
            yaxis: {
                tickAmount: 7,
                labels: {
                    formatter: (value: number) => {
                        return 'Rp ' + value ? value.toLocaleString('id-ID') : value;
                    },
                    offsetX: -10,
                    offsetY: 0,
                    style: {
                        fontSize: '12px',
                        cssClass: 'apexcharts-yaxis-title',
                    },
                },
                opposite: false,
            },
            grid: {
                borderColor: isDark ? '#191E3A' : '#E0E6ED',
                strokeDashArray: 5,
                xaxis: {
                    lines: {
                        show: false,
                    },
                },
                yaxis: {
                    lines: {
                        show: true,
                    },
                },
                padding: {
                    top: 0,
                    right: 0,
                    bottom: 0,
                    left: 0,
                },
            },
            legend: {
                position: 'top',
                horizontalAlign: 'right',
                fontSize: '16px',
                markers: {
                    width: 10,
                    height: 10,
                    offsetX: -2,
                },
                itemMargin: {
                    horizontal: 10,
                    vertical: 5,
                },
            },
            tooltip: {
                marker: {
                    show: true,
                },
                x: {
                    show: false,
                },
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    inverseColors: !1,
                    opacityFrom: isDark ? 0.19 : 0.28,
                    opacityTo: 0.05,
                    stops: isDark ? [100, 100] : [45, 100],
                },
            },
        },
    };

    return (
        <div className="panel h-full xl:col-span-2">
            <div className="mb-5 flex items-center justify-between dark:text-white-light">
                <Dropdown
                    offset={[0, 1]}
                    placement="bottom-start"
                    button={
                        <h5 className="cursor-pointer text-lg font-semibold hover:text-primary">
                            Revenue{' '}
                            <svg className="ml-1 inline h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7"></path>
                            </svg>
                        </h5>
                    }
                >
                    <ul className="rounded-lg bg-white shadow-lg ring-1 ring-gray-300">
                        <li className="border-b last:border-b-0">
                            <button
                                type="button"
                                className="block w-full rounded-md px-4 py-3 text-left text-sm font-medium text-gray-700 transition-colors duration-150 hover:bg-blue-100 hover:text-primary"
                                onClick={() => setShowCart('Transaction')}
                            >
                                <span className="flex items-center justify-between">
                                    <span>Transaction Cart</span>
                                    <svg className="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7"></path>
                                    </svg>
                                </span>
                            </button>
                        </li>
                        <li className="border-b last:border-b-0">
                            <button
                                type="button"
                                className="block w-full rounded-md px-4 py-3 text-left text-sm font-medium text-gray-700 transition-colors duration-150 hover:bg-blue-100 hover:text-primary"
                                onClick={() => setShowCart('Quantity')}
                            >
                                <span className="flex items-center justify-between">
                                    <span>Quantity Cart</span>
                                </span>
                            </button>
                        </li>
                    </ul>
                </Dropdown>
                <div className="dropdown">
                    <Dropdown
                        offset={[0, 1]}
                        placement="bottom-start"
                        button={
                            <svg className="h-5 w-5 text-black/70 hover:!text-primary dark:text-white/70" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <circle cx="5" cy="12" r="2" stroke="currentColor" strokeWidth="1.5" />
                                <circle opacity="0.5" cx="12" cy="12" r="2" stroke="currentColor" strokeWidth="1.5" />
                                <circle cx="19" cy="12" r="2" stroke="currentColor" strokeWidth="1.5" />
                            </svg>
                        }
                    >
                        <ul>
                            <li>
                                <button type="button" onClick={() => setFilterRevenue('weekly')}>
                                    Weekly
                                </button>
                            </li>
                            <li>
                                <button type="button" onClick={() => setFilterRevenue('monthly')}>
                                    Monthly
                                </button>
                            </li>
                            <li>
                                <button type="button" onClick={() => setFilterRevenue('yearly')}>
                                    Yearly
                                </button>
                            </li>
                        </ul>
                    </Dropdown>
                </div>
            </div>
            <p className="text-lg dark:text-white-light/90">
                Total Revenue <span className="ml-2 text-primary">Rp {dataRevenue.totalRevenue ? dataRevenue.totalRevenue.toLocaleString('id-ID') : 0}</span>
            </p>
            <div className="relative">
                <div className="rounded-lg bg-white dark:bg-black">
                    {isMounted ? (
                        <ReactApexChart series={revenueChart.series} options={revenueChart.options} type="area" height={325} width={'100%'} />
                    ) : (
                        <div className="grid min-h-[325px] place-content-center bg-white-light/30 dark:bg-dark dark:bg-opacity-[0.08] ">
                            <span className="inline-flex h-5 w-5 animate-spin rounded-full  border-2 border-black !border-l-transparent dark:border-white"></span>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
export default RevenueDashboard;
