<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\User;
use Livewire\WithPagination;
use App\Traits\WithTableHelpers;
use Livewire\Attributes\Computed;
use App\Support\Currency;
use Livewire\Attributes\On;

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

    public User $user;
    public int $perPage = 10;
    public int $page = 1;
    public string $currencySymbol = '$';
    public array $selected = [];
    public bool $selectAll = false;
    public int $unreadCount = 0;

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

    public function mount(User $user)
    {
        $this->user = $user;

        $profile = $this->user->profile;
        $this->currencySymbol = $profile ? Currency::symbol($profile->currency) : '$';
    }

    #[On('notification-sent')]
    #[On('notifications-read')]
    public function refreshUnreadCount()
    {
        $this->unreadCount = $this->user->unreadNotifications()->count();
    }
    #[Computed]
    public function notifications()
    {
        $query = $this->user->notifications(); // 🔥 This is the key

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

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

    public function markAsRead(string $notificationId)
    {
        $notification = $this->user->notifications()->where('id', $notificationId)->firstOrFail();

        $notification->markAsRead();

        $this->dispatch('showToast', message: 'Notification marked as read', type: 'success');
    }

    public function deleteNotification(string $notificationId)
    {
        $notification = $this->user->notifications()->where('id', $notificationId)->firstOrFail();

        $notification->delete();

        $this->dispatch('showToast', message: 'Notification deleted successfully', type: 'success');
    }

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selected = $this->notifications->pluck('id')->toArray();
        } else {
            $this->selected = [];
        }
    }

    public function bulkMarkAsRead()
    {
        $this->user
            ->notifications()
            ->whereIn('id', $this->selected)
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

        $this->selected = [];
        $this->selectAll = false;

        $this->dispatch('showToast', 'Selected notifications marked as read', type: 'success');
    }

    public function bulkDelete()
    {
        $this->user->notifications()->whereIn('id', $this->selected)->delete();

        $this->selected = [];
        $this->selectAll = false;

        $this->dispatch('showToast', 'Selected notifications deleted', type: 'success');
    }

    public function typeColor($type)
    {
        return match (class_basename($type)) {
            'OrderNotification' => 'bg-blue-100 text-blue-700',
            'PaymentNotification' => 'bg-green-100 text-green-700',
            'WarningNotification' => 'bg-yellow-100 text-yellow-700',
            'AlertNotification' => 'bg-red-100 text-red-700',
            default => 'bg-gray-100 text-gray-700',
        };
    }
    #[Computed]
    public function stats()
    {
        return [
            'total' => $this->user->notifications()->count(),
            'unread' => $this->user->unreadNotifications()->count(),
            'read' => $this->user->readNotifications()->count(),
            'today' => $this->user->notifications()->whereDate('created_at', today())->count(),
        ];
    }

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


<div class="py-4 space-y-5">
    <x-page-header title="{{ $this->user->name }} Notifications"
        subtitle="View all notifications sent to this user including transaction alerts and system messages."
        rightText="Back to User" back-url="{{ route('admin.users.show', $this->user) }}" />
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">

        <div class="p-4 bg-white dark:bg-gray-800 rounded-xl shadow">
            <div class="text-sm text-gray-500">Total</div>
            <div class="text-2xl font-bold">{{ $this->stats['total'] }}</div>
        </div>

        <div class="p-4 bg-white dark:bg-gray-800 rounded-xl shadow">
            <div class="text-sm text-gray-500">Unread</div>
            <div class="text-2xl font-bold text-yellow-600">
                {{ $this->stats['unread'] }}
            </div>
        </div>

        <div class="p-4 bg-white dark:bg-gray-800 rounded-xl shadow">
            <div class="text-sm text-gray-500">Read</div>
            <div class="text-2xl font-bold text-green-600">
                {{ $this->stats['read'] }}
            </div>
        </div>

        <div class="p-4 bg-white dark:bg-gray-800 rounded-xl shadow">
            <div class="text-sm text-gray-500">Today</div>
            <div class="text-2xl font-bold text-sky-600">
                {{ $this->stats['today'] }}
            </div>
        </div>

    </div>

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

        {{-- SEARCH --}}
        <x-slot name="search">
            <div class="flex items-center justify-between gap-4">
                <div class="flex items-center gap-2">
                    <div>
                        <input type="checkbox" wire:model.live="selectAll">
                    </div>
                    @if (count($this->selected))
                        <div class="flex gap-2">

                            <x-flux::button type="button" variant="primary" color="sky" wire:click="bulkMarkAsRead"
                                size="sm" icon="pencil-square">
                                Mark Selected Read
                            </x-flux::button>

                            <x-flux::button type="button" variant="danger" wire:click="bulkDelete" size="sm"
                                icon="trash"
                                wire:confirm="are you sure you want to delete this selected notification?">
                                Delete Selected
                            </x-flux::button>

                        </div>
                    @endif
                </div>
                <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 notifications..."
                            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>

        {{-- HEAD --}}
        <x-slot name="head" label="select">

            <x-table.head label="" />
            <x-table.head label="ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Type" field="type" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Title" />
            <x-table.head label="Message" />
            <x-table.head label="Status" field="read_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Created" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

        {{-- BODY (DESKTOP) --}}
        <x-slot name="body">
            @forelse ($this->notifications as $notification)
                <x-table.row wire:key="notification-{{ $notification->id }}"
                    class="{{ !$notification->read_at ? 'bg-sky-50 dark:bg-sky-900/20' : '' }}">
                    <x-table.cell>
                        <input type="checkbox" value="{{ $notification->id }}" wire:model.live="selected">
                    </x-table.cell>
                    {{-- ID --}}
                    <x-table.cell>
                        {{ \Illuminate\Support\Str::limit($notification->id, 8) }}
                    </x-table.cell>

                    {{-- Type --}}
                    <x-table.cell>
                        <span
                            class="px-2 py-1 text-xs rounded-full 
        {{ $this->typeColor($notification->type) }}">
                            {{ class_basename($notification->type) }}
                        </span>
                    </x-table.cell>

                    {{-- Title --}}
                    <x-table.cell>
                        <div class="font-medium text-gray-900 dark:text-white">
                            {{ $notification->data['title'] ?? 'Notification' }}
                        </div>
                    </x-table.cell>

                    {{-- Message --}}
                    <x-table.cell>
                        <div class="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                            {{ $notification->data['message'] ?? '-' }}
                        </div>
                    </x-table.cell>

                    {{-- Status --}}
                    <x-table.cell>
                        @if ($notification->read_at)
                            <span
                                class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300">
                                Read
                            </span>
                        @else
                            <span
                                class="px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300">
                                Unread
                            </span>
                        @endif
                    </x-table.cell>

                    {{-- Created --}}
                    <x-table.cell>
                        <span title="{{ $notification->created_at->toDayDateTimeString() }}">
                            {{ $notification->created_at->diffForHumans() }}
                        </span>
                    </x-table.cell>

                    {{-- Actions --}}
                    <x-table.cell class="flex gap-2">

                        @if (!$notification->read_at)
                            <x-flux::button type="button" variant="primary" color="sky"
                                wire:click="markAsRead('{{ $notification->id }}')" size="sm" icon="pencil-square">
                                Mark Read
                            </x-flux::button>
                        @endif

                        <x-flux::button type="button" variant="danger"
                            wire:click="deleteNotification('{{ $notification->id }}')" size="sm" icon="trash"
                            wire:confirm="are you sure you want to delete this notification?">
                            Delete
                        </x-flux::button>

                    </x-table.cell>

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

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->notifications as $notification)
                <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
                       {{ !$notification->read_at ? 'border-l-4 border-sky-500' : '' }}">

                    {{-- Title + Time --}}
                    <div class="flex items-start justify-between mb-2">
                        <div class="flex flex-col space-y-1">
                            <span class="font-semibold text-gray-900 dark:text-gray-200">
                                {{ $notification->data['title'] ?? 'Notification' }}
                            </span>

                            <span class="text-sm text-gray-500 dark:text-gray-400">
                                {{ $notification->data['message'] ?? '-' }}
                            </span>
                        </div>

                        <span class="text-xs text-gray-400 dark:text-gray-500">
                            {{ $notification->created_at->diffForHumans() }}
                        </span>
                    </div>

                    {{-- Status --}}
                    <div class="mb-3">
                        @if ($notification->read_at)
                            <span
                                class="inline-flex items-center px-2 py-1 text-xs rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300">
                                Read
                            </span>
                        @else
                            <span
                                class="inline-flex items-center px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300">
                                Unread
                            </span>
                        @endif
                    </div>

                    {{-- Actions --}}
                    <div class="mt-3 flex flex-col sm:flex-row gap-2">

                        @if (!$notification->read_at)
                            <x-flux::button type="button" variant="primary" color="sky"
                                wire:click="markAsRead('{{ $notification->id }}')" size="sm"
                                icon="pencil-square">
                                Mark Read
                            </x-flux::button>
                        @endif

                        <x-flux::button type="button" variant="danger"
                            wire:click="deleteNotification('{{ $notification->id }}')" size="sm" icon="trash"
                            wire:confirm="are you sure you want to delete this notification?">
                            Delete
                        </x-flux::button>
                    </div>

                </x-table.mobile-card>
            @empty
                <div class="px-6 py-8 text-center text-gray-400 dark:text-gray-500">
                    No notifications 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->notifications->links() }}</div>
            </div>
        </x-slot>

    </x-table.wrapper>
</div>
