<?php

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

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

    public User $user;
    public int $perPage = 10;
    public int $page = 1;
    public ?UserEmail $selectedEmail = null;

    // No need to store userEmails; use a computed property
    #[Computed]
    public function userEmails()
    {
        $query = $this->user->emails()->latest();

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

        // Apply sorting
        if (in_array($this->sortField, ['subject', 'status', 'created_at'])) {
            $query->orderBy($this->sortField, $this->sortDirection);
        }

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

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

    public function deleteEmail(int $emailId)
    {
        $email = $this->user->emails()->findOrFail($emailId);
        $email->delete();
        $this->dispatch('success', 'Email deleted successfully.');
    }

    public function viewEmail(int $emailId)
    {
        $this->selectedEmail = $this->user->emails()->findOrFail($emailId);
        $this->dispatch('open-email-modal'); // dispatch event to open modal
    }
    public function closeModal()
    {
        $this->selectedEmail = null;
        $this->dispatch('close-email-modal'); // closes modal
    }
};
?>

<div class="py-4 space-y-5">

    <x-page-header title="{{ $this->user->name }} Email History"
        subtitle="View all emails sent to users, including status, timestamps, and content." rightText="back to user"
        back-url="{{ route('admin.users.show', $this->user) }}">
    </x-page-header>


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

        {{-- 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 or email"
                            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="Subject" sortable field="subject" :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Message" />
            <x-table.head label="Status" sortable field="status" :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Attachments" />
            <x-table.head label="Sent At" sortable field="created_at" :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

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

                    <x-table.cell>{{ $email->subject ?? '_' }}</x-table.cell>


                    <x-table.cell>
                        @php
                            $truncated = Str::limit($email->message, 80);
                            $isTruncated = strlen($email->message) > 80;
                        @endphp
                        {{ $truncated }}
                    </x-table.cell>



                    <x-table.cell>
                        @if ($email->isSent())
                            <span class="px-2 py-1 rounded-full bg-green-500 text-white text-xs">Sent</span>
                        @else
                            <span class="px-2 py-1 rounded-full bg-red-500 text-white text-xs">Failed</span>
                        @endif
                    </x-table.cell>

                    <x-table.cell>{{ $email->attachmentCount() }}</x-table.cell>

                    <x-table.cell>{{ $email->created_at->diffForHumans() }}</x-table.cell>

                    {{-- Action --}}
                    <x-table.cell>
                        <x-flux::button type="button" wire:click="viewEmail({{ $email->id }})" variant="primary"
                            color="sky" icon="eye">
                            View
                        </x-flux::button>

                        <!-- Delete Button -->
                        <x-flux::button type="button" variant="danger" x-data icon="trash"
                            @click.prevent="if (confirm('Are you sure you want to delete this email?')) { $wire.deleteEmail({{ $email->id }}) }">
                            Delete
                        </x-flux::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 emails found
                    </td>
                </tr>
            @endforelse
        </x-slot>

        <x-slot name="mobile">
            @forelse ($this->userEmails as $email)
                <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">

                    {{-- Subject + Status --}}
                    <div class="flex items-center gap-3 mb-2">
                        <div class="flex flex-col">
                            <span class="font-semibold text-gray-900 dark:text-gray-200">{{ $email->subject }}</span>
                            <span
                                class="text-gray-500 dark:text-gray-400 truncate text-sm">{{ Str::limit($email->message, 60) }}</span>
                        </div>
                        <span
                            class="ml-auto text-xs font-semibold px-2 py-1 rounded-full {{ $email->isSent() ? 'bg-green-500 text-white' : 'bg-red-500 text-white' }}">
                            {{ $email->isSent() ? 'Sent' : 'Failed' }}
                        </span>
                    </div>

                    {{-- Details: Attachments + Sent At --}}
                    <div class="flex flex-col text-sm text-gray-700 dark:text-gray-300 space-y-1">
                        <div class="flex justify-between">
                            <span>Attachments:</span>
                            <span>{{ $email->attachmentCount() }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Sent At:</span>
                            <span>{{ $email->formattedDate() }}</span>
                        </div>
                    </div>

                    {{-- Actions: Delete --}}
                    <div class="mt-3 flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0">
                        <x-flux::button type="button" wire:click="viewEmail({{ $email->id }})" variant="primary"
                            color="sky" icon="eye">
                            View
                        </x-flux::button>
                        {{-- Delete --}}
                        <button x-data
                            @click.prevent="if (confirm('Are you sure you want to delete this email?')) { $wire.delete({{ $email->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 emails 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->userEmails->links() }}</div>
            </div>
        </x-slot>

    </x-table.wrapper>


    <x-modal maxWidth="max-w-4xl" @open-email-modal.window="openModal()" @close-email-modal.window="close()">

        {{-- Header --}}
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold text-gray-800 dark:text-gray-200">{{ $selectedEmail?->subject }}</h2>
            <button @click="open = false; $wire.closeModal()"
                class="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">&times;</button>
        </div>

        {{-- Message Body --}}
        <div class="mb-6">
            <div class="flex justify-between items-center mb-2">
                <h3 class="font-semibold text-gray-800 dark:text-gray-200">Message Body</h3>
                <button
                    @click="navigator.clipboard.writeText(`{{ addslashes($selectedEmail?->message ?? '') }}`).then(() => alert('Message copied!'))"
                    class="px-2 py-1 text-xs rounded bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200">
                    Copy Message
                </button>
            </div>
            <p class="text-gray-700 dark:text-gray-300 whitespace-pre-line">{{ $selectedEmail?->message }}</p>
        </div>

        {{-- Attachments --}}
        <div class="mb-6">
            <div class="flex justify-between items-center mb-2">
                <h3 class="font-semibold text-gray-800 dark:text-gray-200">Attachments</h3>
            </div>

            @if ($selectedEmail?->hasAttachments())
                <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                    @foreach ($selectedEmail->attachments as $attachment)
                        @php
                            $attachmentUrl = Storage::url($attachment);
                            $extension = strtolower(pathinfo($attachment, PATHINFO_EXTENSION));
                            $isImage = in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']);
                        @endphp

                        <div class="flex flex-col items-center bg-gray-100 dark:bg-gray-700 rounded p-2">
                            {{-- Image Preview or File Icon --}}
                            @if ($isImage)
                                <img src="{{ $attachmentUrl }}" alt="{{ basename($attachment) }}"
                                    class="w-24 h-24 object-cover rounded mb-2 border border-gray-300 dark:border-gray-600" />
                            @else
                                <div
                                    class="w-24 h-24 flex items-center justify-center bg-gray-200 dark:bg-gray-600 rounded mb-2 border border-gray-300 dark:border-gray-500 text-gray-800 dark:text-gray-200 text-sm font-semibold">
                                    {{ strtoupper($extension) }}
                                </div>
                            @endif

                            {{-- Filename --}}
                            <span class="truncate text-gray-700 dark:text-gray-200 w-full text-center text-sm mb-1">
                                {{ basename($attachment) }}
                            </span>

                            {{-- Download Button --}}
                            <a href="{{ $attachmentUrl }}" download
                                class="px-2 py-1 text-xs rounded bg-sky-500 text-white hover:bg-sky-600 transition">
                                Download
                            </a>
                        </div>
                    @endforeach
                </div>
            @else
                <p class="text-gray-500 dark:text-gray-400">No attachments</p>
            @endif
        </div>

        {{-- Footer --}}
        <div class="flex justify-between items-center text-sm text-gray-700 dark:text-gray-300">
            <span>Sent At: {{ $selectedEmail?->formattedDate() }}</span>

            <x-flux::button @click="open = false; $wire.closeModal()" type="button" variant="danger">
                Close
            </x-flux::button>
        </div>

    </x-modal>


</div>
