@{
    ViewData["Title"] = "Tarball Report";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <title>Tarball Report</title>
    <style>
        .container {
            width: 1400px; /* Approximate width for A4 aspect ratio */
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        div {
            padding-top: 5px;
            padding-bottom: 5px;
        }

        h4 {
            padding-top: 15px;
            padding-bottom: 5px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            border: 1px solid #ccc;
            padding: 10px;
        }
    </style>
    <!-- DataTables CSS -->
    <link href="~/lib/datatables/datatables.css" rel="stylesheet" />
</head>
<body>
    <div id="app" class="container">
        <div>
            <h4>Month</h4>
            <select v-model="selectedMonth" style="width: 100%; padding: 5px;">
                <option value="" selected>Filter by Month</option>
                <option v-for="month in months" :value="month">{{ month }}</option>
            </select>

            <h4>Year</h4>
            <select v-model="selectedYear" style="width: 100%; padding: 5px;">
                <option value="" selected>Filter by Year</option>
                <option v-for="year in years" :value="year">{{ year }}</option>
            </select>

            <div>
                <button v-on:click="clearFilters" class="btn btn-default" style="margin-top: 20px; margin-bottom: 25px;">Clear Filter</button>
            </div>
        </div>

        <div class="datatable">
            <table id="tarballTable" class="table table-bordered table-hover table-striped" style="width:100%;">
                <thead>
                    <tr>
                        <th>No.</th>
                        <th>Date</th>
                        <th>Station</th>
                        <th>Status</th>
                        <th>PDF</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</body>
</html>

@section Scripts {
    <!-- DataTables JS -->
    <script src="~/lib/datatables/datatables.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                selectedMonth: '',
                selectedYear: '',
                months: [
                    'January', 'February', 'March', 'April', 'May',
                    'June', 'July', 'August', 'September',
                    'October', 'November', 'December'
                ],
                dataFromServer: @Html.Raw(Json.Serialize(Model ?? new List<object>()))
            },
            computed: {
                years() {
                    if (!this.dataFromServer || this.dataFromServer.length === 0) {
                        return []; // Return an empty array if no data is available
                    }

                    // Extract all years from the data
                    const allYears = this.dataFromServer.map(data => new Date(data.date).getFullYear());

                    // Find the minimum and maximum years
                    const minYear = Math.min(...allYears);
                    const maxYear = Math.max(...allYears);

                    // Generate a range of years from minYear to maxYear
                    return Array.from({ length: maxYear - minYear + 1 }, (_, i) => (minYear + i).toString());
                },
                sortedFilteredData() {
                    // If no filters are applied, return all data sorted by descending date
                    if (!this.selectedMonth && !this.selectedYear) {
                        return this.dataFromServer.sort((a, b) => new Date(b.date) - new Date(a.date));
                    }

                    // Filter data by selected month and year
                    const filtered = this.dataFromServer.filter(data => {
                        const date = new Date(data.date);
                        const monthMatches = this.selectedMonth
                            ? date.toLocaleString('default', { month: 'long' }) === this.selectedMonth
                            : true;
                        const yearMatches = this.selectedYear
                            ? date.getFullYear().toString() === this.selectedYear
                            : true;
                        return monthMatches && yearMatches;
                    });

                    // Sort data by date in descending order
                    return filtered.sort((a, b) => new Date(b.date) - new Date(a.date));
                }
            },
            methods: {
                clearFilters() {
                    this.selectedMonth = '';
                    this.selectedYear = '';
                }
            },
            mounted() {
                // Initialize DataTables after Vue has rendered the table
                this.$nextTick(() => {
                    const table = $('#tarballTable').DataTable({
                        "pageLength": 10,
                        "lengthMenu": [5, 10, 15, 20],
                        "responsive": true,
                        "order": [[1, "desc"]], // Default sorting by Date column (descending)
                        "orderMulti": false, // Disable multi-column sorting
                        "columns": [
                            {
                                "data": null,
                                "render": (data, type, row, meta) => meta.row + 1 // Dynamically generate "No."
                            },
                            { "data": "date", "render": (data) => new Date(data).toLocaleDateString('en-GB') },
                            { "data": "station" },
                            {
                                "data": null,
                                "render": () => `
                                    <button class="btn btn-success">Approve</button>
                                    <button class="btn btn-danger">Reject</button>
                                `
                            },
                            {
                                "data": null,
                                "render": (data) => `
                                    <a href="/MMS/Marine/ViewPDF?id=${data.id}" class="btn btn-primary" target="_blank">View PDF</a>
                                    <a href="/MMS/Marine/GenerateReport?id=${data.id}" class="btn btn-primary">Download PDF</a>
                                `
                            }
                        ],
                        "rowCallback": function(row, data, index) {
                            // Update the "No." column to start from 1 for the current page
                            const pageInfo = table.page.info();
                            $('td:first', row).html(pageInfo.start + index + 1);
                        }
                    });

                    // Populate the table with all data on initial load
                    table.rows.add(this.dataFromServer).draw();
                });
            },
            watch: {
                sortedFilteredData() {
                    // Automatically update DataTables whenever the filtered data changes
                    const table = $('#tarballTable').DataTable();
                    table.clear();
                    table.rows.add(this.sortedFilteredData);
                    table.draw();
                }
            }
        });
    </script>
}
