<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Computed;
use App\Models\Ticket;
use App\Models\TicketMessages;
use App\Notifications\TicketReplied;
use App\Traits\WithTableHelpers;
use Livewire\WithFileUploads;
use Livewire\WithPagination;

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

    public $perPage = 15;
    public $selectedTicketId = null;
    public $selectedTicket = null;
    public $adminReply = '';
    public $attachments = [];

    protected function searchableFields(): array
    {
        return ['id', 'user.name', 'user.email', 'subject', 'status'];
    }

    public function selectTicket($ticketId)
    {
        $this->selectedTicketId = $ticketId;
        $this->loadSelectedTicket();
    }

    public function loadSelectedTicket()
    {
        $this->selectedTicket = Ticket::with(['messages.user.profile', 'messages.admin'])->find($this->selectedTicketId);
        $this->adminReply = '';
        $this->attachments = [];
    }

    public function markResolved($ticketId)
    {
        $ticket = Ticket::findOrFail($ticketId);
        $ticket->update(['status' => Ticket::STATUS_RESOLVED]);
        $this->loadSelectedTicket();
    }

    protected $rules = [
        'adminReply' => 'required|string',
        'attachments' => 'nullable|array|max:5',
        'attachments.*' => 'file|max:5120|mimes:jpg,jpeg,png,webp,pdf,doc,docx,xls,xlsx',
    ];

    protected function messages()
    {
        return [
            'adminReply.required' => 'Please write a reply before submitting.',
            'attachments.*.image' => 'Each file must be an image.',
            'attachments.max' => 'You can upload a maximum of 5 attachments.',
            'attachments.*.max' => 'Each attachment must not exceed 5MB.',
            'attachments.*.mimes' => 'Allowed file types: jpg, jpeg, png, webp, pdf, doc, docx, xls, xlsx.',
        ];
    }

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function updatedAttachments()
    {
        if (count($this->attachments) > 5) {
            $this->attachments = array_slice($this->attachments, 0, 5);
            $this->addError('attachments', 'You can upload a maximum of 5 attachments.');
        }
    }

    public function removeAttachment($index)
    {
        unset($this->attachments[$index]);
        $this->attachments = array_values($this->attachments); // reindex
    }

    public function delete($id)
    {
        Ticket::findOrFail($id)->delete();
        $this->dispatch('showToast', message: 'Ticket successfully deleted', type: 'success');
    }

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

    public function sendReply()
    {
        $this->validate();

        $paths = [];
        foreach ($this->attachments as $file) {
            $paths[] = $file->store('tickets', 'public');
        }
        $admin = \Illuminate\Support\Facades\Auth::guard('admin')->user();

        TicketMessages::create([
            'ticket_id' => $this->selectedTicketId,
            'admin_id' => $admin->id,
            'user_id' => null,
            'message' => $this->adminReply,
            'attachments' => $paths, // Save as array
            'is_admin' => true,
        ]);

        // Update ticket status
        $ticket = Ticket::find($this->selectedTicketId);
        $ticket->update(['status' => Ticket::STATUS_IN_PROGRESS]);

        // Notify user
        if ($ticket->user) {
            $ticket->user->notify(new TicketReplied($ticket));
        }

        $this->loadSelectedTicket();
        $this->dispatch('showToast', message: 'Message sent successfully!', type: 'success');
    }

    #[Computed]
    public function tickets()
    {
        /** @var \App\Models\Admin|null $admin */
        $admin = auth('admin')->user();

        $query = Ticket::query()->with(['messages', 'user']);

        // Apply visibility filter only if an admin is logged in
        if ($admin) {
            $query->visibleToAdmin($admin);
        } else {
            // No admin logged in, deny access
            $query->whereRaw('1 = 0');
        }

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

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


<div class="min-h-screen bg-gray-50 dark:bg-gray-950 p-6 space-y-8">

    {{-- Top Controls --}}
    <div class="flex flex-col md:flex-row justify-between items-center gap-4 md:gap-0 mb-6">
        <div class="w-full md:w-1/3">
            <input type="text" wire:model.live="search" placeholder="Search tickets..."
                class="w-full px-4 py-3 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-500 transition" />
        </div>

        <div class="flex items-center space-x-2">
            <label class="text-sm text-gray-600 dark:text-gray-400 font-medium">Show:</label>
            <select wire:model="perPage"
                class="text-sm px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-sky-500 transition">
                <option value="10">10</option>
                <option value="15">15</option>
                <option value="25">25</option>
                <option value="50">50</option>
            </select>
        </div>
    </div>

    <div class="flex flex-col lg:flex-row h-[85vh] bg-gray-100 dark:bg-gray-900">

        <!-- Ticket List -->
        <div class="lg:w-1/3 border-r border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-auto">

            <!-- Header -->
            <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                <h2 class="text-xl font-bold text-gray-800 dark:text-gray-100">Support Tickets</h2>
            </div>

            <!-- Ticket Items -->
            <ul class="divide-y divide-gray-200 dark:divide-gray-700">
                @forelse ($this->tickets as $ticket)
                    <li wire:click="selectTicket({{ $ticket->id }})" tabindex="0" role="button"
                        wire:key="ticket-{{ $ticket->id }}"
                        class="cursor-pointer p-4 hover:bg-gray-50 dark:hover:bg-gray-700 transition 
                   {{ $selectedTicketId === $ticket->id ? 'bg-sky-100 dark:bg-sky-800 border-l-4 border-sky-600' : '' }}">

                        <div class="flex justify-between items-center">
                            <!-- Subject -->
                            <h3 class="font-semibold truncate max-w-[60%] text-gray-800 dark:text-gray-100"
                                title="{{ $ticket->subject }}">
                                {{ $ticket->subject }}
                            </h3>

                            <!-- Status & Priority -->
                            <div class="flex items-center gap-2">
                                <!-- Status Badge -->
                                <span
                                    class="text-xs font-semibold px-2 py-1 rounded-full
                        {{ $ticket->status === 'resolved'
                            ? 'bg-green-200 text-green-800 dark:bg-green-700 dark:text-green-100'
                            : ($ticket->status === 'in_progress'
                                ? 'bg-yellow-200 text-yellow-800 dark:bg-yellow-600 dark:text-yellow-100'
                                : 'bg-red-200 text-red-800 dark:bg-red-700 dark:text-red-100') }}">
                                    {{ ucfirst(str_replace('_', ' ', $ticket->status)) }}
                                </span>

                                <!-- Priority Badge -->
                                <span
                                    class="text-xs font-semibold px-2 py-1 rounded-full
                        {{ $ticket->priority === 'High'
                            ? 'bg-red-100 text-red-700 dark:bg-red-700 dark:text-red-100'
                            : ($ticket->priority === 'Medium'
                                ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-600 dark:text-yellow-100'
                                : 'bg-green-100 text-green-700 dark:bg-green-700 dark:text-green-100') }}">
                                    {{ $ticket->priority }}
                                </span>
                            </div>
                        </div>

                        <!-- Created At -->
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            {{ $ticket->created_at->format('Y-m-d H:i') }}
                        </p>
                    </li>
                @empty
                    <li class="text-gray-500 italic p-4">No tickets found.</li>
                @endforelse
            </ul>

            <!-- Pagination -->
            <div class="p-4">
                {{ $this->tickets->links() }}
            </div>
        </div>


        <!-- Chat & Reply -->
        <div class="lg:w-2/3 flex flex-col bg-white dark:bg-gray-900">
            @if ($selectedTicket)
                <!-- Header -->
                <div
                    class="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center sticky top-0 bg-white dark:bg-gray-900 z-10">
                    <h3 class="text-xl font-bold truncate">{{ $selectedTicket->subject }}</h3>
                    <div class="flex items-center gap-1">
                        <span
                            class="inline-block px-3 py-1 rounded-full font-semibold select-none
                {{ $selectedTicket->status === 'resolved'
                    ? 'bg-green-300 text-green-900'
                    : ($selectedTicket->status === 'in_progress'
                        ? 'bg-yellow-300 text-yellow-900'
                        : 'bg-red-300 text-red-900') }}">
                            {{ ucfirst(str_replace('_', ' ', $selectedTicket->status)) }}
                        </span>

                        <!-- Priority Badge -->
                        <span
                            class="text-xs font-semibold px-2 py-1 rounded-full
                        {{ $selectedTicket->priority === 'High'
                            ? 'bg-red-100 text-red-700 dark:bg-red-700 dark:text-red-100'
                            : ($selectedTicket->priority === 'Medium'
                                ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-600 dark:text-yellow-100'
                                : 'bg-green-100 text-green-700 dark:bg-green-700 dark:text-green-100') }}">
                            {{ $selectedTicket->priority }}
                        </span>
                    </div>
                </div>

                <!-- Messages -->
                <div id="chatWindow" class="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
                    @foreach ($selectedTicket->messages as $msg)
                        <div class="flex items-end {{ $msg->is_admin ? 'justify-start' : 'justify-end' }} gap-2">

                            {{-- Avatar --}}
                            @if ($msg->is_admin)
                                {{-- Admin Avatar --}}
                                @if ($msg->admin?->avatar)
                                    <img src="{{ asset('storage/' . $msg->admin->avatar) }}"
                                        class="w-8 h-8 rounded-full object-cover">
                                @else
                                    <img src="{{ asset('images/admin-avatar.png') }}"
                                        class="w-8 h-8 rounded-full object-cover">
                                @endif
                            @else
                                {{-- User Avatar --}}
                                @if ($msg->user?->profile?->profile_photo)
                                    <img src="{{ asset('storage/' . $msg->user->profile->profile_photo) }}"
                                        class="w-8 h-8 rounded-full object-cover">
                                @else
                                    <div
                                        class="w-8 h-8 rounded-full bg-gray-400 text-white flex items-center justify-center text-xs font-bold">
                                        {{ strtoupper(substr($msg->user?->name ?? 'U', 0, 1)) }}
                                    </div>
                                @endif
                            @endif

                            {{-- Message Bubble --}}
                            <div
                                class="max-w-[70%] px-4 py-2 rounded-xl shadow
        {{ $msg->is_admin
            ? 'bg-sky-50 dark:bg-sky-900 dark:text-sky-200 rounded-tl-none'
            : 'bg-green-50 dark:bg-green-800 dark:text-green-100 rounded-tr-none' }}">

                                @if ($msg->message)
                                    <p class="whitespace-pre-line">{{ $msg->message }}</p>
                                @endif

                                @if ($msg->attachments && count($msg->attachments))
                                    <div class="mt-2 grid gap-2">
                                        @foreach ($msg->attachments as $att)
                                            @if (str_contains($att, '.jpg') || str_contains($att, '.png') || str_contains($att, '.webp'))
                                                <a href="{{ asset('storage/' . $att) }}" target="_blank">
                                                    <img src="{{ asset('storage/' . $att) }}"
                                                        class="w-28 h-28 object-cover rounded-lg shadow-md hover:scale-105 transition-transform cursor-pointer" />
                                                </a>
                                            @else
                                                <a href="{{ asset('storage/' . $att) }}" target="_blank"
                                                    class="text-sky-600 dark:text-sky-300 underline truncate max-w-xs block">
                                                    {{ basename($att) }}
                                                </a>
                                            @endif
                                        @endforeach
                                    </div>
                                @endif

                                <p class="mt-1 text-xs text-gray-500 text-right select-none">
                                    {{ $msg->created_at->format('H:i') }}
                                </p>
                            </div>
                        </div>
                    @endforeach


                </div>


                <!-- WhatsApp-style Reply Box with Preview -->
                <form wire:submit.prevent="sendReply"
                    class="sticky bottom-0 z-10 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 px-4 py-3 space-y-2">

                    <!-- Attachments & Upload Preview -->
                    <div x-data="{ uploading: false, progress: 0 }" x-on:livewire-upload-start="uploading = true"
                        x-on:livewire-upload-finish="uploading = false" x-on:livewire-upload-cancel="uploading = false"
                        x-on:livewire-upload-error="uploading = false"
                        x-on:livewire-upload-progress="progress = $event.detail.progress" class="space-y-2">

                        <!-- File Input -->
                        <label class="flex items-center space-x-2 cursor-pointer text-gray-600 dark:text-gray-300">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                                stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828L18 10.828a4 4 0 10-5.656-5.656l-6.586 6.586a6 6 0 108.486 8.486L20 14.828" />
                            </svg>
                            <span class="text-sm">Attach files (max 5)</span>
                            <input type="file" multiple wire:model="attachments"
                                accept=".jpg,.jpeg,.png,.webp,.pdf,.doc,.docx,.xls,.xlsx" class="hidden">
                        </label>

                        <!-- Upload Progress -->
                        <div x-show="uploading">
                            <progress max="100" x-bind:value="progress"
                                class="w-full h-2 rounded bg-gray-200 dark:bg-gray-700"></progress>
                            <button type="button" wire:click="$cancelUpload('attachments')"
                                class="mt-1 px-3 py-1 bg-red-600 text-white rounded text-sm">Cancel Upload</button>
                        </div>

                        <!-- Previews -->
                        <div class="flex flex-wrap gap-3 mt-2">
                            @foreach ($attachments as $index => $file)
                                <div wire:key="attachment_{{ $index }}"
                                    class="relative w-24 h-24 border rounded p-1 flex flex-col items-center justify-center">
                                    @if (str_contains($file->getMimeType(), 'image'))
                                        <img src="{{ $file->temporaryUrl() }}"
                                            class="w-full h-full object-cover rounded">
                                    @else
                                        <div class="text-xs text-center truncate w-full">
                                            {{ $file->getClientOriginalName() }}</div>
                                    @endif
                                    <button type="button" wire:click="removeAttachment({{ $index }})"
                                        class="absolute top-1 right-1 bg-red-600 text-white w-5 h-5 flex items-center justify-center rounded-full">&times;</button>
                                </div>
                            @endforeach
                        </div>

                        <!-- Validation errors -->
                        @error('attachments')
                            <p class="text-red-600 text-sm">{{ $message }}</p>
                        @enderror
                        @error('attachments.*')
                            <p class="text-red-600 text-sm">{{ $message }}</p>
                        @enderror
                    </div>
                    <!-- Message Input (Full width) -->
                    <x-textarea wire:model.live.blur="adminReply" placeholder="Type a message..." rows="1"
                        class="flex-1 resize-none border border-gray-300 dark:border-gray-700 rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500 dark:focus:ring-sky-400" />
                    <!-- Message Input & Buttons -->
                    <div class="flex items-center space-x-2">


                        <!-- Send Button -->
                        <button type="submit" wire:click="sendReply"
                            class="flex-none bg-sky-600 text-white p-3 rounded-full hover:bg-sky-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                            @if ($attachments === null && trim($adminReply) === '') disabled @endif>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                                viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M5 12h14M12 5l7 7-7 7" />
                            </svg>
                        </button>

                        <!-- Resolve Button -->
                        <button type="button" wire:click="markResolved({{ $selectedTicketId }})"
                            class="flex-none bg-green-600 text-white px-3 py-2 rounded-full hover:bg-green-700 transition">
                            Resolve
                        </button>
                    </div>

                </form>
            @else
                <div class="flex-1 flex items-center justify-center text-gray-500 italic">
                    Select a ticket to view and reply.
                </div>
            @endif
        </div>

    </div>

    <style>
        /* Custom scrollbar like WhatsApp web */
        .custom-scrollbar::-webkit-scrollbar {
            width: 6px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb {
            background-color: rgba(59, 130, 246, 0.5);
            border-radius: 3px;
        }
    </style>

    <script>
        // Auto scroll to bottom when new messages arrive
        const chatWindow = document.getElementById('chatWindow');
        if (chatWindow) chatWindow.scrollTop = chatWindow.scrollHeight;
        Livewire.hook('message.processed', () => {
            if (chatWindow) chatWindow.scrollTop = chatWindow.scrollHeight;
        });
    </script>

</div>
