<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center space-x-2">
            <i class="fas fa-calendar-alt"></i>
            <span>{{ __('Jadwal Kontrol Pasien') }}</span>
        </div>
    </x-slot>

    @push('styles')
    <style>
        /* =============================================
           DATATABLES – KKD THEME OVERRIDE
        ============================================= */

        /* Wrapper */
        #tbl-jadwal_wrapper .dataTables_length label,
        #tbl-jadwal_wrapper .dataTables_filter label,
        #tbl-jadwal_wrapper .dataTables_info {
            color: #475569 !important; /* slate-600 */
            font-size: 0.8125rem;
        }
        .dark #tbl-jadwal_wrapper .dataTables_length label,
        .dark #tbl-jadwal_wrapper .dataTables_filter label,
        .dark #tbl-jadwal_wrapper .dataTables_info {
            color: #94a3b8 !important; /* slate-400 */
        }

        /* Search & Length inputs */
        #tbl-jadwal_wrapper .dataTables_length select,
        #tbl-jadwal_wrapper .dataTables_filter input {
            border: 1px solid #cbd5e1 !important;
            border-radius: 0.5rem !important;
            padding: 0.375rem 0.75rem !important;
            font-size: 0.8125rem !important;
            background-color: #ffffff !important;
            color: #0f172a !important;
            outline: none !important;
            transition: border-color 0.15s, box-shadow 0.15s;
        }
        #tbl-jadwal_wrapper .dataTables_length select:focus,
        #tbl-jadwal_wrapper .dataTables_filter input:focus {
            border-color: #14b8a6 !important;
            box-shadow: 0 0 0 3px rgba(20,184,166,0.2) !important;
        }
        .dark #tbl-jadwal_wrapper .dataTables_length select,
        .dark #tbl-jadwal_wrapper .dataTables_filter input {
            background-color: #1e293b !important;
            border-color: #475569 !important;
            color: #f1f5f9 !important;
        }
        .dark #tbl-jadwal_wrapper .dataTables_filter input::placeholder {
            color: #64748b !important;
        }

        /* Table head */
        #tbl-jadwal thead th {
            background-color: #f8fafc !important;
            color: #64748b !important;
            font-size: 0.6875rem !important;
            font-weight: 700 !important;
            text-transform: uppercase !important;
            letter-spacing: 0.05em !important;
            border-bottom: 2px solid #e2e8f0 !important;
            padding: 0.75rem 1rem !important;
            white-space: nowrap;
        }
        .dark #tbl-jadwal thead th {
            background-color: #1e293b !important;
            color: #94a3b8 !important;
            border-bottom: 2px solid #334155 !important;
        }

        /* Sort icons teal */
        #tbl-jadwal thead th.sorting_asc::after  { color: #14b8a6 !important; }
        #tbl-jadwal thead th.sorting_desc::after { color: #14b8a6 !important; }
        #tbl-jadwal thead th.sorting::before,
        #tbl-jadwal thead th.sorting::after { color: #94a3b8 !important; }

        /* Table body */
        #tbl-jadwal tbody td {
            padding: 0.875rem 1rem !important;
            vertical-align: middle !important;
            border-bottom: 1px solid #f1f5f9 !important;
            font-size: 0.875rem;
            color: #334155;
        }
        .dark #tbl-jadwal tbody td {
            border-bottom: 1px solid #1e293b !important;
            color: #cbd5e1 !important;
        }

        /* Row hover */
        #tbl-jadwal tbody tr:hover td {
            background-color: #f0fdfa !important; /* teal-50 */
        }
        .dark #tbl-jadwal tbody tr:hover td {
            background-color: rgba(20,184,166,0.06) !important;
        }

        /* Today row highlight */
        #tbl-jadwal tbody tr.row-today td {
            background-color: #fefce8 !important; /* yellow-50 */
        }
        .dark #tbl-jadwal tbody tr.row-today td {
            background-color: rgba(234,179,8,0.08) !important;
        }

        /* Pagination */
        #tbl-jadwal_wrapper .dataTables_paginate .paginate_button {
            border-radius: 0.5rem !important;
            margin: 0 2px !important;
            font-size: 0.8125rem !important;
            padding: 0.3rem 0.6rem !important;
            border: 1px solid transparent !important;
            color: #475569 !important;
        }
        #tbl-jadwal_wrapper .dataTables_paginate .paginate_button.current,
        #tbl-jadwal_wrapper .dataTables_paginate .paginate_button.current:hover {
            background: #14b8a6 !important;
            border-color: #14b8a6 !important;
            color: #ffffff !important;
            font-weight: 700;
        }
        #tbl-jadwal_wrapper .dataTables_paginate .paginate_button:hover:not(.current):not(.disabled) {
            background: #f0fdfa !important;
            border-color: #99f6e4 !important;
            color: #0d9488 !important;
        }
        .dark #tbl-jadwal_wrapper .dataTables_paginate .paginate_button {
            color: #94a3b8 !important;
        }
        .dark #tbl-jadwal_wrapper .dataTables_paginate .paginate_button:hover:not(.current):not(.disabled) {
            background: rgba(20,184,166,0.12) !important;
            color: #2dd4bf !important;
        }
        .dark #tbl-jadwal_wrapper .dataTables_paginate .paginate_button.disabled,
        #tbl-jadwal_wrapper .dataTables_paginate .paginate_button.disabled {
            color: #cbd5e1 !important;
            cursor: not-allowed;
        }

        /* No records */
        #tbl-jadwal tbody td.dataTables_empty {
            text-align: center;
            padding: 3rem 1rem !important;
            color: #94a3b8 !important;
            font-size: 0.875rem;
        }

        /* Responsive expand icon */
        #tbl-jadwal tbody td.dtr-control::before {
            background-color: #14b8a6 !important;
            box-shadow: 0 0 0 2px rgba(20,184,166,0.3) !important;
        }

        /* Top/bottom bar spacing */
        #tbl-jadwal_wrapper .dataTables_length,
        #tbl-jadwal_wrapper .dataTables_filter {
            margin-bottom: 1rem;
        }
        #tbl-jadwal_wrapper .dataTables_info,
        #tbl-jadwal_wrapper .dataTables_paginate {
            margin-top: 1rem;
        }
    </style>
    @endpush

    <div class="py-6 sm:py-10">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

            {{-- Header Stats --}}
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
                <div class="kkd-card text-center py-4">
                    <div class="stat-value text-2xl text-teal-600 dark:text-teal-400">{{ $jadwal->count() }}</div>
                    <div class="stat-label mt-1">Total Jadwal</div>
                </div>
                <div class="kkd-card text-center py-4">
                    <div class="stat-value text-2xl text-yellow-500">
                        {{ $jadwal->filter(fn($j) => $j->tanggal_kontrol_berikutnya && $j->tanggal_kontrol_berikutnya->isToday())->count() }}
                    </div>
                    <div class="stat-label mt-1">Hari Ini</div>
                </div>
                <div class="kkd-card text-center py-4">
                    <div class="stat-value text-2xl text-red-500">
                        {{ $jadwal->filter(fn($j) => $j->tanggal_kontrol_berikutnya && $j->tanggal_kontrol_berikutnya->isPast() && !$j->tanggal_kontrol_berikutnya->isToday())->count() }}
                    </div>
                    <div class="stat-label mt-1">Terlewat</div>
                </div>
                <div class="kkd-card text-center py-4">
                    <div class="stat-value text-2xl text-slate-700 dark:text-slate-200">
                        {{ $jadwal->filter(fn($j) => $j->status_penanganan == 'AKTIF')->count() }}
                    </div>
                    <div class="stat-label mt-1">Aktif</div>
                </div>
            </div>

            {{-- Main Table Card --}}
            <div class="kkd-card">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
                    <div>
                        <h3 class="section-title flex items-center gap-2">
                            <span class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-teal-100 dark:bg-teal-900/40">
                                <i class="fas fa-calendar-check text-teal-600 dark:text-teal-400 text-sm"></i>
                            </span>
                            Jadwal Kontrol Berikutnya
                        </h3>
                        <p class="section-subtitle mt-1">Klik header kolom untuk mengurutkan data</p>
                    </div>
                    {{-- Legend --}}
                    <div class="flex flex-wrap gap-2 text-xs">
                        <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300 font-medium border border-yellow-200 dark:border-yellow-800">
                            <span class="w-2 h-2 rounded-full bg-yellow-400"></span> Hari ini
                        </span>
                        <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 font-medium border border-red-200 dark:border-red-800">
                            <span class="w-2 h-2 rounded-full bg-red-400"></span> Terlewat
                        </span>
                    </div>
                </div>

                {{-- DataTable --}}
                <div class="overflow-x-auto">
                    <table id="tbl-jadwal" class="min-w-full" style="width:100%">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Pasien</th>
                                <th>No. RM</th>
                                <th>Tanggal Kontrol</th>
                                <th>Keterangan</th>
                                <th>Diagnosis</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($jadwal as $index => $item)
                                @php
                                    $isToday = $item->tanggal_kontrol_berikutnya && $item->tanggal_kontrol_berikutnya->isToday();
                                    $isPast  = $item->tanggal_kontrol_berikutnya && $item->tanggal_kontrol_berikutnya->isPast() && !$isToday;
                                    $tglSort = $item->tanggal_kontrol_berikutnya
                                        ? $item->tanggal_kontrol_berikutnya->format('Y-m-d')
                                        : '9999-12-31';
                                @endphp
                                <tr class="{{ $isToday ? 'row-today' : '' }}">
                                    {{-- # --}}
                                    <td class="text-slate-500 dark:text-slate-400 font-mono text-xs">{{ $loop->iteration }}</td>

                                    {{-- Pasien (dengan avatar) --}}
                                    <td>
                                        <div class="flex items-center gap-2.5">
                                            <div class="w-8 h-8 rounded-full bg-gradient-to-br from-teal-400 to-teal-600 flex items-center justify-center flex-shrink-0 shadow-sm">
                                                <span class="text-white font-bold text-xs">
                                                    {{ strtoupper(substr($item->pasien->nama_lengkap, 0, 2)) }}
                                                </span>
                                            </div>
                                            <span class="font-semibold text-slate-800 dark:text-slate-100 whitespace-nowrap">
                                                {{ $item->pasien->nama_lengkap }}
                                            </span>
                                        </div>
                                    </td>

                                    {{-- No RM --}}
                                    <td>
                                        <span class="font-mono text-xs text-slate-500 dark:text-slate-400">
                                            {{ $item->pasien->no_rekam_medis }}
                                        </span>
                                    </td>

                                    {{-- Tanggal Kontrol (data-sort untuk sorting benar) --}}
                                    <td data-sort="{{ $tglSort }}">
                                        @if($item->tanggal_kontrol_berikutnya)
                                            <span class="font-semibold {{ $isToday ? 'text-yellow-700 dark:text-yellow-400' : ($isPast ? 'text-red-600 dark:text-red-400' : 'text-slate-800 dark:text-slate-100') }}">
                                                {{ $item->tanggal_kontrol_berikutnya->format('d/m/Y') }}
                                            </span>
                                        @else
                                            <span class="text-slate-400 italic text-xs">Belum dijadwalkan</span>
                                        @endif
                                    </td>

                                    {{-- Keterangan waktu --}}
                                    <td>
                                        @if($item->tanggal_kontrol_berikutnya)
                                            @if($isToday)
                                                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 border border-yellow-200 dark:border-yellow-800">
                                                    <span class="w-1.5 h-1.5 rounded-full bg-yellow-400 animate-pulse"></span> Hari ini
                                                </span>
                                            @elseif($isPast)
                                                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 border border-red-200 dark:border-red-800">
                                                    <i class="fas fa-exclamation-circle text-xs"></i>
                                                    Terlewat {{ $item->tanggal_kontrol_berikutnya->diffForHumans() }}
                                                </span>
                                            @else
                                                <span class="text-xs text-slate-400 dark:text-slate-500">
                                                    {{ $item->tanggal_kontrol_berikutnya->diffForHumans() }}
                                                </span>
                                            @endif
                                        @else
                                            <span class="text-slate-300 dark:text-slate-600 text-xs">—</span>
                                        @endif
                                    </td>

                                    {{-- Diagnosis --}}
                                    <td class="text-slate-700 dark:text-slate-300 max-w-xs">
                                        <span title="{{ $item->diagnosis_utama ?? '' }}">
                                            {{ Str::limit($item->diagnosis_utama ?? '-', 35) }}
                                        </span>
                                    </td>

                                    {{-- Status --}}
                                    <td>
                                        @if($item->status_penanganan == 'AKTIF')
                                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300 border border-teal-200 dark:border-teal-800">
                                                <span class="w-1.5 h-1.5 rounded-full bg-teal-500"></span> Aktif
                                            </span>
                                        @else
                                            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300">
                                                {{ $item->status_penanganan }}
                                            </span>
                                        @endif
                                    </td>

                                    {{-- Aksi --}}
                                    <td>
                                        <a href="{{ route('dokter.pasien.detail', $item->pasien_id) }}"
                                           class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold
                                                  bg-teal-600 hover:bg-teal-700 dark:bg-teal-500 dark:hover:bg-teal-600
                                                  text-white transition-colors duration-150 shadow-sm whitespace-nowrap">
                                            <i class="fas fa-eye text-xs"></i> Detail
                                        </a>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>

    @push('scripts')
    <script>
    $(document).ready(function () {

        var isDark = document.documentElement.classList.contains('dark');

        var table = $('#tbl-jadwal').DataTable({
            responsive: true,
            pageLength: 15,
            lengthMenu: [[10, 15, 25, 50, -1], [10, 15, 25, 50, 'Semua']],
            order: [[3, 'asc']], // urutkan berdasar tanggal kontrol
            language: {
                url: 'https://cdn.datatables.net/plug-ins/1.13.4/i18n/id.json',
                search:         '',
                searchPlaceholder: 'Cari pasien, diagnosis...',
                lengthMenu:    'Tampilkan _MENU_ data',
                info:          'Menampilkan _START_–_END_ dari _TOTAL_ jadwal',
                infoEmpty:     'Tidak ada jadwal',
                infoFiltered:  '(difilter dari _MAX_ total)',
                paginate: {
                    first:    '<i class="fas fa-angle-double-left"></i>',
                    last:     '<i class="fas fa-angle-double-right"></i>',
                    previous: '<i class="fas fa-angle-left"></i>',
                    next:     '<i class="fas fa-angle-right"></i>',
                },
                emptyTable:    'Tidak ada jadwal kontrol',
                zeroRecords:   'Tidak ditemukan jadwal yang sesuai',
            },
            columnDefs: [
                { orderable: false, targets: [4, 7] }, // Keterangan & Aksi tidak bisa diurutkan
                { type: 'date', targets: [3] },        // Kolom tanggal
                { responsivePriority: 1, targets: [1] }, // Nama pasien selalu tampil
                { responsivePriority: 2, targets: [7] }, // Aksi selalu tampil
                { responsivePriority: 3, targets: [3] }, // Tanggal kontrol
                { responsivePriority: 4, targets: [6] }, // Status
            ],
            drawCallback: function () {
                // Re-apply row-today class setelah redraw
                this.api().rows().every(function () {
                    var $row = $(this.node());
                    if ($row.hasClass('row-today')) {
                        $row.find('td').css({
                            'background-color': isDark ? 'rgba(234,179,8,0.08)' : '#fefce8'
                        });
                    }
                });
            },
            initComplete: function () {
                // Style the search input container
                var $filter = $('#tbl-jadwal_wrapper .dataTables_filter');
                $filter.find('label').contents().filter(function () {
                    return this.nodeType === 3;
                }).remove();
            }
        });

        // Watch dark mode toggle and redraw to re-apply styles
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (m) {
                if (m.attributeName === 'class') {
                    isDark = document.documentElement.classList.contains('dark');
                    table.draw(false);
                }
            });
        });
        observer.observe(document.documentElement, { attributes: true });
    });
    </script>
    @endpush

</x-app-layout>