<?php

use Livewire\Component;
use Livewire\WithPagination;
use App\Traits\WithTableHelpers;
use App\Models\Ticket;
use Illuminate\Support\Facades\Auth;

new class extends Component {
    use WithPagination, WithTableHelpers;

    public int $perPage = 10;
    public int $page = 1;

    protected function searchableFields(): array
    {
        return ['id', 'priority', 'status'];
    }

    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }

    public function getTicketsProperty()
    {
        $query = Ticket::with([
            'messages' => function ($q) {
                // Only get the latest message for each ticket
                $q->latest('updated_at')->limit(1);
            },
        ])->where('user_id', Auth::id());

        // Apply search
        if ($this->search) {
            $query->where(function ($q) {
                $q->where('subject', 'like', "%{$this->search}%")
                    ->orWhere('priority', 'like', "%{$this->search}%")
                    ->orWhere('status', 'like', "%{$this->search}%");
            });
        }

        // Apply sorting
        $query->orderBy($this->sortField ?? 'created_at', $this->sortDirection ?? 'desc');

        return $query->paginate($this->perPage);
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || All Support Ticket
</x-slot:title>

<div class="py-4">
    <div class="flex items-end justify-end">
        <a href="{{ route('user.ticket.create') }}"
            class="bg-sky-600 text-white flex items-center hover:shadow-2xl justify-center gap-1 px-3 py-2 rounded-md">
            <x-flux::icon.send class="w-4 h-4" />
            <span class="text-sm font-medium">Create Ticket</span>
        </a>
    </div>
    <x-table.wrapper :items="$this->tickets">

        {{-- SEARCH --}}
        <x-slot name="search">
            <div class="flex items-center justify-between gap-4">

                <div class="w-full md:w-1/3">
                    <div class="relative">
                        <x-flux::icon.magnifying-glass
                            class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
                        <input type="text" wire:model.live="search" placeholder="Search tickets..."
                            class="w-full pl-10 pr-4 py-2 text-sm rounded-md bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-600 focus:border-sky-600 transition" />
                    </div>
                </div>

            </div>
        </x-slot>

        {{-- HEADERS --}}
        <x-slot name="head">
            <x-table.head label="Ticket ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Subject" field="subject" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Priority" field="priority" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Last Updated" field="updated_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Created At" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

        {{-- BODY --}}
        <x-slot name="body">
            @forelse ($this->tickets as $ticket)
                <x-table.row wire:key="row-{{ $ticket->id }}"
                    class="hover:shadow-lg transition-shadow duration-200 rounded-lg mb-2">

                    <x-table.cell class="font-semibold text-gray-900 dark:text-gray-200">
                        #{{ $ticket->id }}
                    </x-table.cell>

                    <x-table.cell class="text-gray-700 dark:text-gray-300">
                        {{ $ticket->subject }}
                    </x-table.cell>

                    <x-table.cell class="capitalize text-gray-700 dark:text-gray-300">
                        {{ $ticket->priority }}
                    </x-table.cell>

                    <x-table.cell>
                        @php
                            $statusGradient = match ($ticket->status) {
                                'open' => 'bg-gradient-to-r from-blue-400 to-blue-600 text-white',
                                'pending' => 'bg-gradient-to-r from-yellow-400 to-yellow-500 text-black',
                                'in_progress' => 'bg-gradient-to-r from-indigo-400 to-indigo-600 text-white',
                                'resolved' => 'bg-gradient-to-r from-green-400 to-green-600 text-white',
                                'closed' => 'bg-gradient-to-r from-gray-400 to-gray-600 text-white',
                                default => 'bg-gray-300 text-gray-800',
                            };
                        @endphp
                        <span class="px-3 py-1 rounded-full text-xs font-semibold {{ $statusGradient }}">
                            {{ str_replace('_', ' ', ucfirst($ticket->status)) }}
                        </span>
                    </x-table.cell>

                    <x-table.cell class="text-gray-500 dark:text-gray-400 text-sm">
                        @php
                            $lastMessage = $ticket->messages->first();
                        @endphp
                        <span title="{{ $lastMessage?->updated_at?->toDayDateTimeString() }}">
                            {{ $lastMessage?->updated_at?->diffForHumans() ?? '-' }}
                        </span>

                    </x-table.cell>

                    <x-table.cell class="text-gray-500 dark:text-gray-400 text-sm">
                        <span title="{{ $ticket->created_at->toDayDateTimeString() }}">
                            {{ $ticket->created_at->diffForHumans() }}
                        </span>
                    </x-table.cell>

                    <x-table.cell>
                        <a href="{{ route('user.ticket.show', $ticket->id) }}"
                            class="inline-flex w-full items-center justify-center gap-2 px-4 py-2 font-medium rounded-lg bg-linear-to-r from-sky-500 to-sky-600 text-white shadow-md hover:from-sky-600 hover:to-sky-700 transition-all duration-200 capitalize text-xs">
                            <!-- View Icon -->
                            <x-flux::icon.eye variant="solid" class="w-4 h-4" />
                            View
                        </a>
                    </x-table.cell>

                </x-table.row>
            @empty
                <tr>
                    <td colspan="6" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">
                        <div class="flex flex-col items-center justify-center gap-2">
                            <div
                                class="w-14 h-14 rounded-full flex items-center justify-center bg-linear-to-r from-blue-400 to-blue-600 text-white">
                                <flux:icon name="inbox" class="w-6 h-6" />
                            </div>
                            <p class="text-gray-700 dark:text-gray-300 text-lg font-medium">No tickets found</p>
                        </div>
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->tickets as $ticket)
                <x-table.mobile-card
                    class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 mb-4 hover:shadow-xl transition duration-200">

                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-sm font-semibold text-gray-900 dark:text-gray-200">Ticket #{{ $ticket->id }}
                        </h3>
                        <span
                            class="text-xs font-semibold px-3 py-1 rounded-full
                        {{ $ticket->status === 'open'
                            ? 'bg-gradient-to-r from-blue-400 to-blue-600 text-white'
                            : ($ticket->status === 'pending'
                                ? 'bg-gradient-to-r from-yellow-400 to-yellow-500 text-black'
                                : ($ticket->status === 'in_progress'
                                    ? 'bg-gradient-to-r from-indigo-400 to-indigo-600 text-white'
                                    : ($ticket->status === 'resolved'
                                        ? 'bg-gradient-to-r from-green-400 to-green-600 text-white'
                                        : 'bg-gray-300 text-gray-800'))) }}">
                            {{ str_replace('_', ' ', ucfirst($ticket->status)) }}
                        </span>
                    </div>

                    <div class="space-y-2 text-sm text-gray-700 dark:text-gray-300">
                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Subject:</span>
                            <span>{{ $ticket->subject }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Priority:</span>
                            <span class="capitalize">{{ $ticket->priority }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Last Updated At:</span>
                            @php
                                $lastMessage = $ticket->messages->first();
                            @endphp
                            <span title="{{ $lastMessage?->updated_at?->toDayDateTimeString() }}">
                                {{ $lastMessage?->updated_at?->diffForHumans() ?? '-' }}
                            </span>

                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Created:</span>
                            <span
                                title="{{ $ticket->created_at->toDayDateTimeString() }}">{{ $ticket->created_at->diffForHumans() }}</span>
                        </div>
                    </div>

                    <a href="{{ route('user.ticket.show', $ticket->id) }}"
                        class="mt-4 inline-flex w-full items-center justify-center gap-2 px-4 py-2 text-sm font-medium rounded-lg bg-linear-to-r from-sky-500 to-sky-600 text-white shadow-md hover:from-sky-600 hover:to-sky-700 transition-all duration-200 capitalize">
                        <x-flux::icon.eye variant="solid" class="w-5 h-5" />
                        View Ticket
                    </a>

                </x-table.mobile-card>
            @empty
                <div class="px-6 py-6 text-center text-gray-400 dark:text-gray-500">
                    No tickets found
                </div>
            @endforelse
        </x-slot>

        {{-- FOOTER --}}
        <x-slot name="footer">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between w-full gap-4 mt-6"
                x-data="{
                    open: false,
                    options: [5, 10, 15, 20, 25, 50],
                    selected: @js($perPage)
                }" x-init="$watch('selected', value => $wire.set('perPage', value));
                Livewire.on('perPageUpdated', event => selected = event.value);"
                x-transition:enter="transition-opacity ease-out duration-500" x-transition:enter-start="opacity-0"
                x-transition:enter-end="opacity-100" x-transition:leave="transition-opacity ease-in duration-300"
                x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">

                <!-- Rows Per Page Selector -->
                <div class="relative text-sm w-fit">
                    <label class="block text-gray-700 dark:text-gray-300 mb-1 text-xs font-medium">
                        Rows per page
                    </label>

                    <button @click="open = !open"
                        class="w-36 bg-white dark:bg-gray-800 text-gray-800 dark:text-white border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 flex justify-between items-center shadow-sm hover:border-gray-400 dark:hover:border-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-500"
                        type="button" aria-haspopup="listbox" aria-expanded="open">
                        <span x-text="selected"></span>
                        <svg class="w-4 h-4 ml-2 transform transition-transform duration-200"
                            :class="{ 'rotate-180': open }" fill="none" viewbox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                        </svg>
                    </button>

                    <!-- Dropdown -->
                    <div x-show="open" @click.outside="open = false"
                        x-transition:enter="transition ease-out duration-100"
                        x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
                        x-transition:leave="transition ease-in duration-75"
                        x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-95"
                        class="absolute bottom-0 mt-2 w-full z-50 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg">
                        <ul class="py-1 max-h-60 overflow-auto text-sm text-gray-800 dark:text-white">
                            <template x-for="option in options" :key="option">
                                <li>
                                    <a href="#" @click.prevent="selected = option; open = false"
                                        class="block px-4 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700"
                                        :class="{ 'bg-gray-100 dark:bg-gray-700 font-semibold': selected === option }"
                                        x-text="option"></a>
                                </li>
                            </template>
                        </ul>
                    </div>
                </div>

                <!-- Pagination Links -->
                <div class="w-full md:w-auto text-center">{{ $this->tickets->links() }}</div>
            </div>
        </x-slot>

    </x-table.wrapper>

</div>
