@extends('layouts.app')

@section('content')
    <div class="space-y-6">
        <div>
            <h2 class="text-2xl font-semibold text-slate-900">Pesanan Hari Ini</h2>
            <p class="text-sm text-slate-500">Pilih tipe order baru atau lanjutkan pesanan berjalan.</p>
        </div>

        <div class="grid gap-4 md:grid-cols-2">
            <x-card class="bg-gradient-to-br from-slate-900 to-slate-700 text-white">
                <h3 class="text-xl font-semibold text-white">Take Away</h3>
                <p class="mt-1 text-sm text-slate-100">Order cepat tanpa meja. Cocok untuk pickup.</p>
                <x-button href="{{ route('orders.create', ['type' => 'take_away']) }}" class="mt-4 bg-amber-200 text-slate-900 hover:bg-amber-300" data-clear-order-storage>Mulai Take Away</x-button>
            </x-card>
            <x-card class="bg-gradient-to-br from-emerald-700 to-emerald-500 text-white">
                <h3 class="text-xl font-semibold text-white">Dine In</h3>
                <p class="mt-1 text-sm text-emerald-50">Order dengan meja. Pastikan nomor meja terisi.</p>
                <x-button href="{{ route('orders.create', ['type' => 'dine_in']) }}" class="mt-4 bg-emerald-100 text-emerald-900 hover:bg-emerald-200" data-clear-order-storage>Mulai Dine In</x-button>
            </x-card>
        </div>

        <x-card>
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-semibold text-slate-900">Order Aktif Hari Ini</h3>
                <!-- <x-button href="{{ route('orders.create') }}" variant="secondary">Tambah Pesanan</x-button> -->
            </div>

            <div class="mt-4 flex flex-wrap items-center gap-3">
                <input
                    id="orders-search"
                    name="q"
                    placeholder="Cari meja atau pelanggan"
                    value="{{ $search }}"
                    class="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700 shadow-sm focus:border-amber-400 focus:ring-amber-200 md:w-80"
                />

                <div id="orders-filters" class="flex flex-wrap items-center gap-2 text-xs">
                    @php($statusFilter = $status ?: 'all')
                    <a href="{{ route('orders.index', array_merge(request()->query(), ['status' => null])) }}"
                       class="rounded-full border px-3 py-1 font-semibold {{ $statusFilter === 'all' ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 text-slate-500 hover:bg-slate-100' }}">
                        Semua
                    </a>
                    <a href="{{ route('orders.index', array_merge(request()->query(), ['status' => 'open'])) }}"
                       class="rounded-full border px-3 py-1 font-semibold {{ $statusFilter === 'open' ? 'border-emerald-600 bg-emerald-600 text-white' : 'border-slate-200 text-slate-500 hover:bg-slate-100' }}">
                        Open
                    </a>
                    <a href="{{ route('orders.index', array_merge(request()->query(), ['status' => 'closed'])) }}"
                       class="rounded-full border px-3 py-1 font-semibold {{ $statusFilter === 'closed' ? 'border-sky-600 bg-sky-600 text-white' : 'border-slate-200 text-slate-500 hover:bg-slate-100' }}">
                        Closed
                    </a>
                </div>
            </div>

            <div id="orders-list" class="mt-4 grid gap-4 md:grid-cols-2">
                @forelse($orders as $order)
                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-4">
                        <div class="flex items-center justify-between">
                            <div class="text-sm font-semibold text-slate-900">{{ $order->order_no }}</div>
                            <x-badge :variant="$order->status === 'open' ? 'success' : ($order->status === 'closed' ? 'info' : 'danger')">
                                {{ ucfirst($order->status) }}
                            </x-badge>
                        </div>
                        <div class="mt-2 text-sm text-slate-500">
                            {{ $order->tanggal->format('d-m-Y H:i') }} - {{ $order->type === 'dine_in' ? 'Dine In' : 'Take Away' }}
                        </div>
                        <div class="mt-1 text-sm text-slate-500">
                            @if($order->type === 'dine_in')
                                Meja: {{ $order->meja?->no_meja ?? '-' }}
                                @if($order->meja_tambahan)
                                    <div class="mt-1 text-xs text-slate-500">
                                        Meja tambahan: {{ $order->meja_tambahan }}
                                    </div>
                                @endif
                            @else
                                Pelanggan: {{ $order->nama_pelanggan ?? '-' }}
                            @endif
                        </div>
                        <div class="mt-2 text-sm font-semibold text-slate-700">Total {{ format_rupiah($order->grand_total) }}</div>
                        <x-button href="{{ route('orders.show', $order) }}" variant="secondary" class="mt-3 w-full">Detail / Tambah Item</x-button>
                    </div>
                @empty
                    <div class="rounded-xl border border-dashed border-slate-200 p-6 text-center text-sm text-slate-500">
                        Belum ada order. Mulai dengan memilih Take Away atau Dine In.
                    </div>
                @endforelse
            </div>

            <div id="orders-pagination" class="mt-4">{{ $orders->links() }}</div>
        </x-card>
    </div>

    <script>
        document.querySelectorAll('[data-clear-order-storage]').forEach((btn) => {
            btn.addEventListener('click', () => {
                try {
                    localStorage.removeItem('order_cart_items');
                    localStorage.removeItem('order_header_inputs');
                } catch (error) {
                    // ignore storage errors
                }
            });
        });

        let ordersReloadTimer;
        const ordersSearch = document.getElementById('orders-search');
        const ordersList = document.getElementById('orders-list');
        const ordersPagination = document.getElementById('orders-pagination');
        let ordersSearchTimer;
        let isFetchingOrders = false;
        const ORDERS_DEBOUNCE = 500;

        function fetchOrders(url) {
            if (isFetchingOrders) return;
            isFetchingOrders = true;
            ordersList?.classList.add('opacity-60');

            fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then((res) => res.text())
                .then((html) => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');

                    const newList = doc.querySelector('#orders-list');
                    const newPagination = doc.querySelector('#orders-pagination');
                    const newFilters = doc.querySelector('#orders-filters');

                    if (newList && ordersList) ordersList.innerHTML = newList.innerHTML;
                    if (newPagination && ordersPagination) ordersPagination.innerHTML = newPagination.innerHTML;
                    if (newFilters) document.getElementById('orders-filters').innerHTML = newFilters.innerHTML;

                    rebindOrdersLinks();
                    window.history.replaceState({}, '', url);
                })
                .finally(() => {
                    ordersList?.classList.remove('opacity-60');
                    isFetchingOrders = false;
                });
        }

        function updateOrdersQuery(value) {
            const url = new URL(window.location.href);
            if (value) {
                url.searchParams.set('q', value);
            } else {
                url.searchParams.delete('q');
            }
            url.searchParams.set('page', '1');
            fetchOrders(url.toString());
        }

        ordersSearch?.addEventListener('input', () => {
            const value = ordersSearch.value.trim();
            clearTimeout(ordersSearchTimer);
            ordersSearchTimer = setTimeout(() => {
                updateOrdersQuery(value);
            }, ORDERS_DEBOUNCE);
        });

        function rebindOrdersLinks() {
            document.querySelectorAll('#orders-pagination a').forEach((link) => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    fetchOrders(link.href);
                });
            });
            document.querySelectorAll('#orders-filters a').forEach((link) => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    const url = new URL(link.href);
                    url.searchParams.set('page', '1');
                    fetchOrders(url.toString());
                });
            });
        }

        function showOrderToast(message) {
            const toast = document.createElement('div');
            toast.className = 'fixed right-6 top-20 z-50 flex items-center gap-3 rounded-xl bg-slate-900 px-4 py-3 text-sm text-white shadow-lg';
            toast.innerHTML = `
                <span class="inline-flex h-8 w-8 items-center justify-center rounded-full bg-emerald-500/20 text-emerald-200">
                    <svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                        <path d="M16.707 5.293a1 1 0 0 1 0 1.414l-8 8a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L8 12.586l7.293-7.293a1 1 0 0 1 1.414 0Z"/>
                    </svg>
                </span>
                <div>${message}</div>
            `;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 2400);
        }

        window.addEventListener('orders-realtime', (event) => {
            clearTimeout(ordersReloadTimer);
            const orderNo = event.detail?.order_no ? ` (${event.detail.order_no})` : '';
            const message = event.detail?.status === 'open'
                ? `Order baru masuk${orderNo}.`
                : `Order diperbarui${orderNo}.`;
            showOrderToast(message);
            ordersReloadTimer = setTimeout(() => {
                const url = new URL(window.location.href);
                fetchOrders(url.toString());
            }, 1200);
        });

        rebindOrdersLinks();
    </script>

    @if(session('print_order_id'))
        <script>
            const printUrl = "{{ route('orders.print', session('print_order_id')) }}";
            const printWindow = window.open(printUrl, '_blank');
            if (printWindow) {
                printWindow.focus();
            }
        </script>
    @endif
@endsection
