@extends('layouts.admin')

@section('title', 'Credit Notes')

@section('page-title', 'Credit Notes')

@section('breadcrumbs')
    <span class="text-primary font-medium">Credit Notes</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    @if(session('success'))
        <div class="mb-4 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
            {{ session('success') }}
        </div>
    @endif
    @if(session('info'))
        <div class="mb-4 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800">
            {{ session('info') }}
        </div>
    @endif

    <!-- Header Section -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Credit Notes</h1>
        <div class="flex items-center gap-3">
            <form method="GET" action="{{ route('admin.credit-notes.index') }}" class="flex items-center">
                @if(request('search'))
                    <input type="hidden" name="search" value="{{ request('search') }}">
                @endif
                <select name="per_page" onchange="this.form.submit()" class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
                    <option value="10" {{ request('per_page', 10) == 10 ? 'selected' : '' }}>10 / page</option>
                    <option value="25" {{ request('per_page', 10) == 25 ? 'selected' : '' }}>25 / page</option>
                    <option value="50" {{ request('per_page', 10) == 50 ? 'selected' : '' }}>50 / page</option>
                    <option value="100" {{ request('per_page', 10) == 100 ? 'selected' : '' }}>100 / page</option>
                </select>
            </form>
            <a href="{{ route('admin.credit-notes.create') }}" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined text-lg">add</span>
                <span>New Credit Note</span>
            </a>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <form method="GET" action="{{ route('admin.credit-notes.index') }}" class="flex gap-2">
            @if(request('per_page'))
                <input type="hidden" name="per_page" value="{{ request('per_page') }}">
            @endif
            <input type="text" name="search" value="{{ request('search') }}" placeholder="Search credit notes..." class="flex-1 max-w-md h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors" title="Search">
                <span class="material-symbols-outlined">search</span>
            </button>
            @if(request('search'))
                <a href="{{ route('admin.credit-notes.index', ['per_page' => request('per_page')]) }}" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors" title="Clear search">
                    <span class="material-symbols-outlined">close</span>
                </a>
            @endif
        </form>
    </div>

    <!-- Credit Notes Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 w-16">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[140px]">Credit note #</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[140px]">Invoice</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[180px]">Customer</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[120px]">Date</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[120px]">Amount</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[100px]">Status</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[80px]">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100" id="credit-notes-tbody">
                    @forelse($creditNotes as $index => $creditNote)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-6 text-sm text-gray-600">{{ ($creditNotes->currentPage() - 1) * $creditNotes->perPage() + $index + 1 }}</td>
                            <td class="py-4 px-6">
                                <a href="{{ route('admin.credit-notes.show', $creditNote) }}" class="text-sm font-medium text-primary hover:underline">{{ $creditNote->credit_note_number }}</a>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                @if($creditNote->invoice)
                                    <span class="font-medium text-gray-900">{{ $creditNote->invoice->invoice_number }}</span>
                                @else
                                    <span class="text-gray-400">—</span>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-900">
                                {{ $creditNote->customer?->name ?? $creditNote->invoice?->customer?->name ?? '—' }}
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $creditNote->credit_note_date?->format('M d, Y') ?? '—' }}
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                                {{ \App\Models\Currency::formatAmount((float) $creditNote->total, $creditNote->currency ?? null) }}
                            </td>
                            <td class="py-4 px-6">
                                @php
                                    $status = $creditNote->status ?? 'pending';
                                    $statusClasses = [
                                        'pending' => 'bg-yellow-100 text-yellow-800',
                                        'approved' => 'bg-green-100 text-green-800',
                                        'rejected' => 'bg-red-100 text-red-800',
                                    ];
                                @endphp
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusClasses[$status] ?? $statusClasses['pending'] }}">
                                    {{ ucfirst($status) }}
                                </span>
                            </td>
                            <td class="py-4 px-6 text-right">
                                <div class="relative inline-block">
                                    <button type="button" onclick="cnToggleActionMenu({{ $creditNote->id }}, event)" class="text-gray-400 hover:text-gray-600 transition-colors" title="More actions">
                                        <span class="material-symbols-outlined text-xl">more_vert</span>
                                    </button>
                                    <div id="cn-action-menu-{{ $creditNote->id }}" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-50">
                                        <div class="py-1">
                                            <a href="{{ route('admin.credit-notes.show', $creditNote) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors">
                                                <span class="material-symbols-outlined text-base">visibility</span>
                                                <span>View</span>
                                            </a>
                                            <div class="border-t border-gray-100 my-1"></div>
                                            <button type="button" onclick="cnOpenDeleteModal({{ $creditNote->id }}, @json($creditNote->credit_note_number))" class="w-full flex items-center gap-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors text-left">
                                                <span class="material-symbols-outlined text-base">delete</span>
                                                <span>Delete</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">note_add</span>
                                <p>No credit notes found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if($creditNotes->hasPages())
            <div class="px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row items-center justify-between gap-4">
                <p class="text-sm text-gray-500">
                    Showing <span class="font-medium text-gray-900">{{ $creditNotes->firstItem() }}</span> to <span class="font-medium text-gray-900">{{ $creditNotes->lastItem() }}</span> of <span class="font-medium text-gray-900">{{ $creditNotes->total() }}</span> entries
                </p>
                <div class="flex items-center gap-1">
                    @if($creditNotes->onFirstPage())
                        <button type="button" disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">&lt;</button>
                    @else
                        <a href="{{ $creditNotes->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">&lt;</a>
                    @endif

                    @php
                        $currentPage = $creditNotes->currentPage();
                        $lastPage = $creditNotes->lastPage();
                        $startPage = max(1, $currentPage - 1);
                        $endPage = min($lastPage, $currentPage + 1);
                    @endphp

                    @if($startPage > 1)
                        <a href="{{ $creditNotes->url(1) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">1</a>
                        @if($startPage > 2)
                            <span class="px-3 py-1 text-sm text-gray-500">...</span>
                        @endif
                    @endif

                    @for($page = $startPage; $page <= $endPage; $page++)
                        <a href="{{ $creditNotes->url($page) }}" class="px-3 py-1 text-sm rounded {{ $page == $currentPage ? 'bg-primary text-white' : 'text-gray-500 hover:bg-gray-50' }}">
                            {{ $page }}
                        </a>
                    @endfor

                    @if($endPage < $lastPage)
                        @if($endPage < $lastPage - 1)
                            <span class="px-3 py-1 text-sm text-gray-500">...</span>
                        @endif
                        <a href="{{ $creditNotes->url($lastPage) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">{{ $lastPage }}</a>
                    @endif

                    @if($creditNotes->hasMorePages())
                        <a href="{{ $creditNotes->nextPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">&gt;</a>
                    @else
                        <button type="button" disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">&gt;</button>
                    @endif
                </div>
            </div>
        @elseif($creditNotes->total() > 0)
            <div class="px-6 py-4 border-t border-gray-200">
                <p class="text-sm text-gray-500">
                    Showing <span class="font-medium text-gray-900">{{ $creditNotes->total() }}</span> {{ Str::plural('entry', $creditNotes->total()) }}
                </p>
            </div>
        @endif
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="cn-deleteModal" data-admin-modal class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md m-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">Delete credit note</h3>
            <p class="text-sm text-gray-600 mb-6">Are you sure you want to delete credit note <span id="cn-delete-number" class="font-medium"></span>? This action cannot be undone.</p>
            <div class="flex items-center justify-end gap-3">
                <button type="button" onclick="cnCloseDeleteModal()" class="px-4 py-2 text-sm text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                    Cancel
                </button>
                <form id="cn-delete-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="px-4 py-2 text-sm text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                        Delete
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
function cnToggleActionMenu(id, event) {
    event.stopPropagation();
    const menu = document.getElementById('cn-action-menu-' + id);
    document.querySelectorAll('[id^="cn-action-menu-"]').forEach(function(m) {
        if (m.id !== 'cn-action-menu-' + id) {
            m.classList.add('hidden');
        }
    });
    menu.classList.toggle('hidden');
}

document.addEventListener('click', function() {
    document.querySelectorAll('[id^="cn-action-menu-"]').forEach(function(menu) {
        menu.classList.add('hidden');
    });
});

function cnOpenDeleteModal(id, number) {
    document.getElementById('cn-delete-number').textContent = number;
    document.getElementById('cn-delete-form').action = '{{ route('admin.credit-notes.index') }}/' + id;
    var modal = document.getElementById('cn-deleteModal');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function cnCloseDeleteModal() {
    var modal = document.getElementById('cn-deleteModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}
</script>
@endpush
@endsection
