<script>
    $(document).ready(function () {
        'use strict';

        const $chartArea = $("#user-transactions-chart");
        const $daterangeTransactions = $('#user-daterange-transactions');

        let transactions = @json($transactionsStatistics);
        let chart = null;

        initializeDateRangePicker();
        createTransactionChart(transactions);

        function initializeDateRangePicker() {
            $daterangeTransactions.daterangepicker({
                opens: 'left'
            }, function(start, end) {
                fetchTransactionsData(start, end);
            });
        }

        function fetchTransactionsData(start, end) {
            const startDate = start.format('YYYY-MM-DD');
            const endDate = end.format('YYYY-MM-DD');
            $.ajax({
                url: '{{ route('admin.users.manage', $user->id) }}',
                method: 'GET',
                data: { start_date: startDate, end_date: endDate },
                dataType: 'json',
                success: function(data) {
                    console.log('Data fetched:', data);
                    transactions = data;
                    updateTransactionChart(transactions);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('Error fetching transaction data:', textStatus, errorThrown);
                }
            });
        }

        function createTransactionChart(transactionsData) {
            const transactionDates = Object.keys(transactionsData);


            // Adjusting date parsing for "Oct 13" format
            const validTransactionDates = transactionDates.map(date => {
                const parsedDate = moment(date, 'MMM DD', true); // Match "Oct 13" format
                return parsedDate.isValid() ? parsedDate.toISOString() : null; // Convert to ISO if valid
            }).filter(date => date); // Filter out invalid dates



            const transactionsPendingArrayValues = [];
            const transactionsCompletedArrayValues = [];
            const transactionsCanceledArrayValues = [];

            validTransactionDates.forEach((date, index) => {
                const originalDate = transactionDates[index];
                const transaction = transactionsData[originalDate];


                transactionsPendingArrayValues.push(transaction?.pending ?? 0);
                transactionsCompletedArrayValues.push(transaction?.completed ?? 0);
                transactionsCanceledArrayValues.push(transaction?.failed ?? 0);
            });


            const chartOptions = {
                chart: {
                    type: "area",
                    fontFamily: 'inherit',
                    height: 240,
                    parentHeightOffset: 0,
                    toolbar: { show: false },
                    animations: { enabled: false }
                },
                dataLabels: { enabled: false },
                stroke: { width: 2, lineCap: "round", curve: "smooth" },
                series: [
                    { name: "Pending", data: transactionsPendingArrayValues },
                    { name: "Completed", data: transactionsCompletedArrayValues },
                    { name: "Canceled", data: transactionsCanceledArrayValues }
                ],
                tooltip: { theme: 'dark' },
                grid: {
                    padding: { top: -20, right: 0, left: -4, bottom: -4 },
                    strokeDashArray: 4
                },
                xaxis: {
                    labels: { padding: 0 },
                    axisBorder: { show: false },
                    tooltip: { enabled: false },
                    type: 'datetime',
                    categories: validTransactionDates // Use valid dates for categories
                },
                yaxis: { labels: { padding: 4 } },
                labels: validTransactionDates,
                legend: {
                    show: true,
                    position: 'bottom',
                    offsetY: 12,
                    markers: { width: 10, height: 10, radius: 100 },
                    itemMargin: { horizontal: 8, vertical: 8 }
                }
            };

            // Destroy existing chart instance if it exists
            if (chart) {
                chart.destroy();
            }

            // Create new chart instance and render
            chart = new ApexCharts($chartArea[0], chartOptions);
            chart.render();
        }

        function updateTransactionChart(transactionsData) {
            if (chart) {
                const transactionDates = Object.keys(transactionsData);

                // Adjusting date parsing for "Oct 13" format
                const validTransactionDates = transactionDates.map(date => {
                    const parsedDate = moment(date, 'MMM DD', true);
                    return parsedDate.isValid() ? parsedDate.toISOString() : null;
                }).filter(date => date);

                const transactionsPendingArrayValues = [];
                const transactionsCompletedArrayValues = [];
                const transactionsCanceledArrayValues = [];

                validTransactionDates.forEach((date, index) => {
                    const originalDate = transactionDates[index];
                    const transaction = transactionsData[originalDate];

                    transactionsPendingArrayValues.push(transaction?.pending ?? 0);
                    transactionsCompletedArrayValues.push(transaction?.completed ?? 0);
                    transactionsCanceledArrayValues.push(transaction?.failed ?? 0);
                });


                chart.updateSeries([
                    { name: "Pending", data: transactionsPendingArrayValues },
                    { name: "Completed", data: transactionsCompletedArrayValues },
                    { name: "Canceled", data: transactionsCanceledArrayValues }
                ]);

                chart.updateOptions({
                    xaxis: {
                        categories: validTransactionDates
                    },
                    labels: validTransactionDates
                });
            }
        }

        createTransactionChart(transactions);
    });

</script>

