@extends('layouts.app')

@section('content')
<div class="container-fluid py-4">


    {{-- Alerts --}}
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            {{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @php
        $containers = $containers ?? [];
        $totalContainers = count($containers);
        $totalWeight = 0;
        foreach($containers as $container) {
            if (isset($container['weight_kg']) && is_numeric($container['weight_kg'])) {
                $totalWeight += (float) $container['weight_kg'];
            }
        }
    @endphp

    {{-- Statistics Cards --}}
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-primary">
                <div class="card-body text-center">
                    <h3 class="text-primary mb-0">{{ $totalContainers }}</h3>
                    <small class="text-muted">Total Containers</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-success">
                <div class="card-body text-center">
                    <h3 class="text-success mb-0">{{ number_format($totalWeight / 1000, 1) }}</h3>
                    <small class="text-muted">Total Weight (tons)</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-info">
                <div class="card-body text-center">
                    @php
                        $fullContainers = count(array_filter($containers, fn($c) => ($c['status'] ?? '') === 'F'));
                    @endphp
                    <h3 class="text-info mb-0">{{ $fullContainers }}</h3>
                    <small class="text-muted">Full Containers</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-warning">
                <div class="card-body text-center">
                    @php
                        $emptyContainers = count(array_filter($containers, fn($c) => ($c['status'] ?? '') === 'E'));
                    @endphp
                    <h3 class="text-warning mb-0">{{ $emptyContainers }}</h3>
                    <small class="text-muted">Empty Containers</small>
                </div>
            </div>
        </div>
    </div>

    @if(!empty($containers) && count($containers) > 0)
    {{-- Container List --}}
    <div class="card">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">
                <i class="bi bi-boxes"></i> Container List
            </h5>
            <span class="badge bg-light text-dark">{{ count($containers) }} containers</span>
        </div>
        <div class="card-body p-0">
            {{-- Search and Filter --}}
            <div class="row px-3 pt-3 mb-3">
                <div class="col-md-4">
                    <input type="text" id="searchInput" class="form-control form-control-sm" placeholder="Search container...">
                </div>
                <div class="col-md-3">
                    <select id="statusFilter" class="form-select form-select-sm">
                        <option value="">All Status</option>
                        <option value="F">Full Only</option>
                        <option value="E">Empty Only</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <select id="portFilter" class="form-select form-select-sm">
                        <option value="">All Ports</option>
                        @php
                            $uniquePorts = array_unique(array_filter(array_column($containers, 'pod_locode')));
                            sort($uniquePorts);
                        @endphp
                        @foreach($uniquePorts as $port)
                            <option value="{{ $port }}">{{ $port }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <button id="clearFilters" class="btn btn-outline-secondary btn-sm w-100">
                        <i class="bi bi-x-circle"></i> Clear
                    </button>
                </div>
            </div>

            {{-- Table --}}
            <div class="table-responsive px-3 pb-3">
                <table class="table table-striped table-hover table-sm mb-0" style="font-size: 0.85rem;">
                    <thead class="table-dark">
                        <tr>
                            <th style="width: 40px;">No</th>
                            <th>Container No</th>
                            <th>ISO Type</th>
                            <th>Size</th>
                            <th>Status</th>
                            <th class="text-end">Weight (kg)</th>
                            <th>Position</th>
                            <th>PoL</th>
                            <th>PoD</th>
                            <th>Delivery</th>
                            <th>Operator</th>
                            <th>B/L Number</th>
                            <th>Handling</th>
                            <th style="width: 90px;" class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="containerTableBody">
                        {{-- Rows akan di-render oleh JS --}}
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            <div class="d-flex justify-content-between align-items-center px-3 pb-3">
                <div>
                    <select id="rowsPerPageSelect" class="form-select form-select-sm" style="width: auto;">
                        <option value="10">10 per page</option>
                        <option value="25" selected>25 per page</option>
                        <option value="50">50 per page</option>
                        <option value="100">100 per page</option>
                    </select>
                </div>
                <div>
                    <button id="prevPage" class="btn btn-outline-primary btn-sm me-2" disabled>
                        <i class="bi bi-chevron-left"></i> Previous
                    </button>
                    <span id="pageInfo" class="fw-semibold me-2"></span>
                    <button id="nextPage" class="btn btn-outline-primary btn-sm" disabled>
                        Next <i class="bi bi-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const containers = @json($containers);
            let rowsPerPage = 25;
            let currentPage = 1;
            let filteredData = containers;

            const tbody = document.getElementById('containerTableBody');
            const prevBtn = document.getElementById('prevPage');
            const nextBtn = document.getElementById('nextPage');
            const pageInfo = document.getElementById('pageInfo');
            const searchInput = document.getElementById('searchInput');
            const statusFilter = document.getElementById('statusFilter');
            const portFilter = document.getElementById('portFilter');
            const clearFiltersBtn = document.getElementById('clearFilters');
            const rowsPerPageSelect = document.getElementById('rowsPerPageSelect');

            // Fungsi helper
            function simplifySize(sizeRaw) {
                if (!sizeRaw) return 'N/A';
                const size = sizeRaw.toString().trim();
                if (size.startsWith('20')) return "20'";
                if (size.startsWith('40')) return "40'";
                if (size.startsWith('45')) return "45'";
                return 'N/A';
            }

            function getStatusBadge(status) {
                if (status === 'F') return '<span class="badge bg-success">Full</span>';
                if (status === 'E') return '<span class="badge bg-warning text-dark">Empty</span>';
                return '<span class="badge bg-secondary">N/A</span>';
            }

            function renderTable(page, data) {
                tbody.innerHTML = '';

                if (data.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="14" class="text-center text-muted py-4">
                                <i class="bi bi-inbox" style="font-size: 2rem; opacity: 0.5;"></i>
                                <br>No containers found with current filters
                            </td>
                        </tr>
                    `;
                    pageInfo.textContent = 'No results';
                    prevBtn.disabled = true;
                    nextBtn.disabled = true;
                    return;
                }

                const start = (page - 1) * rowsPerPage;
                const end = start + rowsPerPage;
                const pageData = data.slice(start, end);

                pageData.forEach((container, index) => {
                    const globalIndex = start + index;
                    const no = start + index + 1;
                    const weight = (container.weight_kg && !isNaN(container.weight_kg)) ?
                        Number(container.weight_kg).toLocaleString() : 'N/A';
                    const position = (container.bay && container.row && container.tier) ?
                        `${String(container.bay).padStart(3,'0')}-${String(container.row).padStart(2,'0')}-${String(container.tier).padStart(2,'0')}` :
                        'N/A';

                    const pol = container.pol_locode ? `<span class="badge bg-info">${container.pol_locode}</span>` : '<span class="text-muted">N/A</span>';
                    const pod = container.pod_locode ? `<span class="badge bg-info">${container.pod_locode}</span>` : '<span class="text-muted">N/A</span>';
                    const delivery = container.delivery_locode ? `<span class="badge bg-info">${container.delivery_locode}</span>` : '<span class="text-muted">N/A</span>';

                    // Find original index in containers array
                    const originalIndex = containers.findIndex(c =>
                        c.container_no === container.container_no &&
                        c.bay === container.bay &&
                        c.row === container.row &&
                        c.tier === container.tier
                    );

                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${no}</td>
                        <td><strong>${container.container_no || 'N/A'}</strong></td>
                        <td>${container.iso_type || 'N/A'}</td>
                        <td>${simplifySize(container.size || container.iso_type)}</td>
                        <td>${getStatusBadge(container.status)}</td>
                        <td class="text-end">${weight}</td>
                        <td>${position}</td>
                        <td>${pol}</td>
                        <td>${pod}</td>
                        <td>${delivery}</td>
                        <td>${container.operator_code || 'N/A'}</td>
                        <td>${container.bl_no || 'N/A'}</td>
                        <td>${container.handling_instruction || 'N/A'}</td>
                        <td class="text-center">
                            <a href="/containers/${originalIndex}/edit"
                               class="btn btn-sm btn-outline-primary"
                               title="Edit Container">
                                <i class="bi bi-pencil"></i>
                            </a>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });

                const totalPages = Math.ceil(data.length / rowsPerPage);
                pageInfo.textContent = `Page ${page} of ${totalPages} (${data.length} total)`;
                prevBtn.disabled = page === 1;
                nextBtn.disabled = page === totalPages;
            }

            function applyFilters() {
                const searchTerm = searchInput.value.toUpperCase();
                const statusValue = statusFilter.value;
                const portValue = portFilter.value;

                filteredData = containers.filter(container => {
                    // Search filter
                    const matchesSearch = !searchTerm || Object.values(container).some(val =>
                        val && val.toString().toUpperCase().includes(searchTerm)
                    );

                    // Status filter
                    const matchesStatus = !statusValue || container.status === statusValue;

                    // Port filter
                    const matchesPort = !portValue || container.pod_locode === portValue;

                    return matchesSearch && matchesStatus && matchesPort;
                });

                currentPage = 1;
                renderTable(currentPage, filteredData);
            }

            function clearFilters() {
                searchInput.value = '';
                statusFilter.value = '';
                portFilter.value = '';
                applyFilters();
            }

            // Event listeners
            searchInput.addEventListener('input', applyFilters);
            statusFilter.addEventListener('change', applyFilters);
            portFilter.addEventListener('change', applyFilters);
            clearFiltersBtn.addEventListener('click', clearFilters);

            rowsPerPageSelect.addEventListener('change', function() {
                rowsPerPage = parseInt(this.value);
                currentPage = 1;
                renderTable(currentPage, filteredData);
            });

            prevBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderTable(currentPage, filteredData);
                }
            });

            nextBtn.addEventListener('click', () => {
                if (currentPage < Math.ceil(filteredData.length / rowsPerPage)) {
                    currentPage++;
                    renderTable(currentPage, filteredData);
                }
            });

            // Initial render
            renderTable(currentPage, filteredData);
        });
    </script>
    @else
    {{-- Empty State --}}
    <div class="card">
        <div class="card-body text-center py-5">
            <i class="bi bi-inbox" style="font-size: 4rem; opacity: 0.3; color: #6c757d;"></i>
            <h4 class="mt-3 text-muted">No Containers Found</h4>
            <p class="text-muted">Upload a BAPLIE file to see containers here.</p>
            <a href="{{ route('dashboard') }}" class="btn btn-primary">
                <i class="bi bi-upload"></i> Upload BAPLIE File
            </a>
        </div>
    </div>
    @endif
</div>
@endsection
