<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\User;
use App\Models\UserLogin;
use Livewire\WithPagination;
use App\Traits\WithTableHelpers;
use Livewire\Attributes\Computed;

new #[Layout('layouts::base')] class extends Component {
    use WithPagination, WithTableHelpers;

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

    protected function searchableFields(): array
    {
        return ['id', 'ip_address', 'location', 'browser', 'device', 'platform', 'login_at'];
    }

    // Computed property for logins
    #[Computed]
    public function logins()
    {
        $query = UserLogin::where('user_id', $this->user->id)->with('user');

        $this->applySearch($query, $this->searchableFields());

        return $query
            ->orderBy($this->sortField ?? 'created_at', $this->sortDirection ?? 'desc')
            ->paginate($this->perPage)
            ->withQueryString();
    }

    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }
    public function deleteLogin(int $loginId)
    {
        $login = $this->user->userlogins()->findOrFail($loginId);
        $login->delete();
        $this->dispatch('showToast', 'login successfully deleted', type: 'success');
    }
};
?>

<div class="py-4 space-y-5">
    <x-page-header title="{{ $this->user->name }} Login History"
        subtitle="View all login attempts, including device, IP address, and timestamps." rightText="back to user"
        back-url="{{ route('admin.users.show', $this->user) }}">
    </x-page-header>


    <x-table.wrapper :items="$this->logins">

        {{-- 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 by name, email, IP..."
                            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 --}}
        {{-- HEADERS --}}
        <x-slot name="head">
            <x-table.head label="Login ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="User" />
            <x-table.head label="IP Address" field="ip_address" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Location" field="location" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Browser" field="browser" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Device" field="device" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Platform" field="platform" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Login Time" field="login_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>


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

                    {{-- Login ID --}}
                    <x-table.cell>{{ $login->id ?? '_' }}</x-table.cell>

                    {{-- User --}}
                    <x-table.cell>
                        <div class="font-medium text-gray-900 dark:text-white">{{ $login->user->name ?? 'N/A' }}</div>
                        <div class="text-sm text-gray-500 dark:text-gray-400 lowercase">
                            {{ $login->user->email ?? 'N/A' }}</div>
                    </x-table.cell>

                    {{-- IP Address --}}
                    <x-table.cell>{{ $login->ip_address ?? 'N/A' }}</x-table.cell>

                    {{-- Location --}}
                    <x-table.cell>{{ $login->location ?? 'N/A' }}</x-table.cell>

                    {{-- Browser --}}
                    <x-table.cell>{{ $login->browser ?? 'N/A' }}</x-table.cell>

                    {{-- Device --}}
                    <x-table.cell>{{ $login->device ?? 'N/A' }}</x-table.cell>

                    {{-- Platform --}}
                    <x-table.cell>{{ $login->platform ?? 'N/A' }}</x-table.cell>

                    {{-- Login Time --}}
                    <x-table.cell>
                        <span title="{{ optional($login->login_at)?->toDayDateTimeString() }}">
                            {{ optional($login->login_at)?->diffForHumans() ?? 'N/A' }}
                        </span>
                    </x-table.cell>

                    {{-- Actions --}}
                    <x-table.cell>
                        <button x-data
                            @click.prevent="if (confirm('Are you sure you want to delete this login record?')) { $wire.delete({{ $login->id }}) }"
                            class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-1 transition">
                            Delete
                        </button>
                    </x-table.cell>

                </x-table.row>
            @empty
                <tr>
                    <td colspan="8" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">
                        No Login History found
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->logins as $login)
                <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">

                    {{-- User + IP --}}
                    <div class="flex items-center justify-between mb-2">
                        <div class="flex flex-col">
                            <span
                                class="font-semibold text-gray-900 dark:text-gray-200">{{ $login->user->name ?? 'N/A' }}</span>
                            <span
                                class="text-gray-500 dark:text-gray-400 text-sm lowercase">{{ $login->user->email ?? 'N/A' }}</span>
                            <span
                                class="text-gray-500 dark:text-gray-400 text-sm">{{ $login->ip_address ?? 'N/A' }}</span>
                        </div>
                        <span
                            class="text-sm text-gray-400 dark:text-gray-500">{{ optional($login->login_at)?->diffForHumans() ?? 'N/A' }}</span>
                    </div>

                    {{-- Device + Browser --}}
                    <div class="flex flex-wrap text-sm text-gray-700 dark:text-gray-300 gap-2 mb-2">
                        <span>Browser: {{ $login->browser ?? 'N/A' }}</span>
                        <span>Device: {{ $login->device ?? 'N/A' }}</span>
                        <span>Platform: {{ $login->platform ?? 'N/A' }}</span>
                        <span>Location: {{ $login->location ?? 'N/A' }}</span>
                    </div>

                    {{-- Actions --}}
                    <div class="mt-3 flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0">
                        <button x-data
                            @click.prevent="if (confirm('Are you sure you want to delete this login record?')) { $wire.delete({{ $login->id }}) }"
                            class="flex-1 inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-lg text-white bg-red-600 hover:bg-red-700 transition">
                            Delete
                        </button>
                    </div>

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

        {{-- FOOTER / PAGINATION --}}
        <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);">

                <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>
                    <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>

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

    </x-table.wrapper>

</div>
