<div class="col-12 col-xxl-8 mb-3 mb-xxl-0">
    <div class="card">
        <div class="card-header d-flex flex-column flex-md-row align-items-md-center gap-2">
            <h3 class="card-title mb-0 me-auto">{{ __('Transactions Statistics') }}</h3>
            <div class="col-auto d-flex gap-2">
                <input type="text" name="daterange" id="dashboard-daterange-transactions" class="form-control"
                       value="{{ $dateRange }}" placeholder="{{ __('Select a date range') }}">
            </div>
        </div>
        <div class="card-body">
            <div id="dashboard-transactions-chart"></div>
        </div>
    </div>
</div>
@push('script')
    <script>
        $(document).ready(function () {
            'use strict';

            // Cache DOM elements
            const $chartArea = $("#dashboard-transactions-chart");
            const $daterangeTransactions = $('#dashboard-daterange-transactions');

            // Get the Laravel-generated data as a JavaScript object
            let transactions = @json($transactionsStatistics);
            let chart = null; // Store the chart instance

            // Initialize the date range picker and chart
            initializeDateRangePicker();
            createTransactionChart(transactions); // Call it initially to load the default data

            // Function to initialize the date range picker
            function initializeDateRangePicker() {
                $daterangeTransactions.daterangepicker({
                    opens: 'left'
                }, function (start, end) {
                    fetchTransactionsData(start, end);
                });
            }

            // Function to fetch data from the server based on date range
            function fetchTransactionsData(start, end) {
                $.ajax({
                    url: '{{ route('admin.dashboard') }}',
                    data: {
                        start_date: start.format('DD-MM-YYYY'),
                        end_date: end.format('DD-MM-YYYY')
                    },
                    method: 'GET',
                    success: function (data) {
                        console.log(data);
                        transactions = data;
                        updateTransactionChart(transactions); // Update the chart with new data
                    },
                    error: function (er) {
                        console.error(er);
                    }
                });
            }

            // Function to create or update the chart
            function createTransactionChart(transactionsData) {
                const transactionDates = Object.keys(transactionsData);
                const transactionsPendingArrayValues = transactionDates.map(key => transactionsData[key].pending ?? 0);
                const transactionsCompletedArrayValues = transactionDates.map(key => transactionsData[key].completed ?? 0);
                const transactionsCanceledArrayValues = transactionDates.map(key => transactionsData[key].failed ?? 0);

                const chartOptions = {
                    chart: {
                        type: "area",
                        height: 320,
                        fontFamily: 'inherit',
                        toolbar: { show: false },
                        animations: { enabled: true }
                    },
                    dataLabels: { enabled: false },
                    stroke: {
                        width: 2,
                        lineCap: "round",
                        curve: "smooth" // Use smooth curve for a spline effect
                    },
                    series: [
                        { name: "Pending", data: transactionsPendingArrayValues },
                        { name: "Completed", data: transactionsCompletedArrayValues },
                        { name: "Canceled", data: transactionsCanceledArrayValues }
                    ],
                    tooltip: {
                        theme: 'dark',
                        x: { format: 'dd MMM' } // Format for the tooltip dates
                    },
                    grid: {
                        padding: { top: -20, right: 0, left: -4, bottom: -4 },
                        strokeDashArray: 4
                    },
                    xaxis: {
                        labels: { rotate: -15 }, // Rotate labels for better visibility
                        type: 'category', // Change to 'category' for better handling of date strings
                        categories: transactionDates,
                        tooltip: { enabled: false }
                    },
                    yaxis: {
                        labels: { padding: 1 }
                    },
                    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 to update the chart data dynamically
            function updateTransactionChart(transactionsData) {
                if (chart) {
                    const transactionDates = Object.keys(transactionsData);
                    const transactionsPendingArrayValues = transactionDates.map(key => transactionsData[key].pending ?? 0);
                    const transactionsCompletedArrayValues = transactionDates.map(key => transactionsData[key].completed ?? 0);
                    const transactionsCanceledArrayValues = transactionDates.map(key => transactionsData[key].failed ?? 0);

                    // Update the chart's series and categories with new data
                    chart.updateSeries([
                        { name: "Pending", data: transactionsPendingArrayValues },
                        { name: "Completed", data: transactionsCompletedArrayValues },
                        { name: "Canceled", data: transactionsCanceledArrayValues }
                    ]);

                    chart.updateOptions({
                        xaxis: {
                            categories: transactionDates
                        },
                        labels: transactionDates
                    });
                }
            }
        });
    </script>
@endpush
