<?php

use Livewire\Component;
use App\Models\Ticket;
use App\Models\TicketMessages;
use Livewire\Attributes\On;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;

new class extends Component {
    use WithFileUploads;

    public Ticket $ticket;
    public $newMessage = '';
    public $replyImages = [];
    public int $ticketId;

    protected $rules = [
        'newMessage' => 'nullable|string',
        'replyImages' => 'nullable|array|max:5', // Max 5 files
        'replyImages.*' => 'file|max:5120|mimes:jpg,jpeg,png,webp,pdf,doc,docx', // 5MB max
    ];

    public function mount(Ticket $ticket)
    {
        if ($ticket->user_id !== Auth::id()) {
            abort(403);
        }

        $this->ticket = $ticket->load('messages.user');
        $this->ticketId = $ticket->id;
    }

    #[On('viewTicket')]
    public function loadTicket(int $id)
    {
        $this->ticketId = $id;
        $this->ticket = Ticket::with('messages.user')->where('user_id', Auth::id())->findOrFail($id);
    }

    #[On('ticketCreated')]
    public function refreshTickets()
    {
        $this->resetPage();
    }

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

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

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

        // Upload attachments first if any
        $storedAttachments = [];
        foreach ($this->replyImages as $file) {
            $storedAttachments[] = $file->store('ticket-files', 'public');
        }

        // Create a single message combining text + attachments
        if ($this->newMessage || !empty($storedAttachments)) {
            TicketMessages::create([
                'ticket_id' => $this->ticketId,
                'user_id' => Auth::id(),
                'message' => $this->newMessage ?? '',
                'attachments' => $storedAttachments ?: null,
                'updated_at' => now(),
                'is_admin' => false,
            ]);
        }

        // Reset input
        $this->newMessage = '';
        $this->replyImages = [];

        $this->dispatch('showToast', message: 'Message Sent.', type: 'success');

        // Reload ticket messages
        $this->ticket = $this->ticket->fresh('messages.user');
    }
};
?>
<x-slot:title>
    {{ config('app.name') }} || Ticket Information
</x-slot:title>
<div class="py-4">
    <div class="flex flex-col h-[80vh] bg-white dark:bg-gray-900 shadow rounded">

        {{-- Header --}}
        <div class="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <div>
                <h2 class="text-lg font-semibold">{{ $ticket->subject }}</h2>
                <p class="text-sm text-gray-500">
                    Status:
                    @php
                        // Define colors for each status
                        $statusColors = [
                            'open' => 'text-sky-600 bg-sky-100',
                            'pending' => 'text-yellow-600 bg-yellow-100',
                            'closed' => 'text-red-600 bg-red-100',
                            'in_progress' => 'text-blue-600 bg-blue-100',
                            'resolved' => 'text-green-600 bg-green-100',
                        ];

                        // Pick color, default to gray
                        $statusKey = $ticket->status;
                        $colorClass = $statusColors[$statusKey] ?? 'text-gray-600 bg-gray-100';

                        // Format status: replace underscores and capitalize each word
                        $formattedStatus = collect(explode('_', $ticket->status))
                            ->map(fn($word) => ucfirst($word))
                            ->implode(' ');
                    @endphp

                    <span class="px-2 py-1 rounded-full font-medium {{ $colorClass }}">
                        {{ $formattedStatus }}
                    </span>
                </p>
            </div>

            <a href="{{ route('user.ticket.index') }}" class="text-sm text-blue-500 hover:underline">
                ← Back
            </a>
        </div>

  <!-- User Messages Container (WhatsApp-style) -->
<div id="messagesContainer" class="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
@foreach ($ticket->messages as $msg)
    <div class="flex mb-4 {{ $msg->is_admin ? 'justify-start' : 'justify-end' }}">

        {{-- LEFT SIDE (Admin Avatar) --}}
        @if ($msg->is_admin)
            <div class="mr-2">
                @if ($msg->admin?->avatar)
                    <img src="{{ Storage::disk('public')->url($msg->admin->avatar) }}"
                         class="w-8 h-8 rounded-full object-cover shadow"
                         alt="Admin avatar" />
                @else
                    <img src="{{ asset('images/admin-avatar.png') }}"
                         class="w-8 h-8 rounded-full object-cover shadow"
                         alt="Admin" />
                @endif
            </div>
        @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' }}">

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

            {{-- ATTACHMENTS --}}
            @if (!empty($msg->attachments))
                <div class="mt-2 grid gap-2">
                    @foreach ($msg->attachments as $att)
                        @php
                            $extension = strtolower(pathinfo($att, PATHINFO_EXTENSION));
                        @endphp

                        @if (in_array($extension, ['jpg', 'jpeg', 'png', 'webp']))
                            <a href="{{ asset('storage/' . $att) }}"
                               target="_blank"
                               class="block">
                                <img src="{{ asset('storage/' . $att) }}"
                                     class="w-28 h-28 object-cover rounded-lg shadow-md hover:scale-105 transition-transform cursor-pointer"
                                     alt="Attachment" />
                            </a>
                        @else
                            <a href="{{ asset('storage/' . $att) }}"
                               target="_blank"
                               class="text-blue-600 underline truncate max-w-xs block">
                                {{ basename($att) }}
                            </a>
                        @endif
                    @endforeach
                </div>
            @endif

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

        {{-- RIGHT SIDE (User Avatar) --}}
        @unless ($msg->is_admin)
            <div class="ml-2">
                @if ($msg->user?->profile?->profile_photo)
                    <img src="{{ Storage::disk('public')->url($msg->user->profile->profile_photo) }}"
                         class="w-8 h-8 rounded-full object-cover shadow"
                         alt="{{ $msg->user->name }}" />
                @else
                    <div class="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center text-sm font-semibold text-gray-700">
                        {{ $msg->user?->initials() ?? 'U' }}
                    </div>
                @endif
            </div>
        @endunless

    </div>
@endforeach

</div>

        <form wire:submit.prevent="sendMessage"
            class="px-4 py-3 border-t border-gray-200 dark:border-gray-700 flex flex-col gap-3"
            enctype="multipart/form-data">

            {{-- Message Input --}}
            <x-textarea wire:model.defer="newMessage" rows="2" placeholder="Type your message..."></x-textarea>

            {{-- File Upload / Drag & Drop --}}
            <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="flex flex-col gap-2">

                <label
                    class="flex flex-col items-center justify-center p-4 border-2 border-dashed rounded-lg cursor-pointer hover:border-blue-500 text-center text-sm text-gray-400 dark:text-gray-500">
                    Click or drag files here
                    <span class="mt-1">JPG, PNG, WEBP, PDF, DOC (max 5MB each)</span>
                    <input type="file" multiple wire:model="replyImages"
                        accept="image/jpeg,image/jpg,image/png,image/webp,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        class="hidden">

                </label>

                {{-- Upload Progress --}}
                <div x-show="uploading" class="w-full">
                    <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('replyImages')"
                        class="mt-1 px-3 py-1 bg-red-600 text-white rounded text-sm">Cancel Upload</button>
                </div>

                {{-- Previews --}}
                @if ($replyImages)
                    <div class="flex flex-wrap gap-2 mt-2">
                        @foreach ($replyImages as $index => $file)
                            <div wire:key="reply_{{ $index }}"
                                class="relative w-28 h-28 border rounded p-2 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>
                @endif

                {{-- Validation Errors --}}
                @error('replyImages')
                    <p class="text-red-500 text-sm">{{ $message }}</p>
                @enderror
                @error('replyImages.*')
                    <p class="text-red-500 text-sm">{{ $message }}</p>
                @enderror
            </div>

            {{-- Send Button --}}
            <div class="flex justify-end">
                <x-button type="submit">
                    Send
                </x-button>
            </div>
        </form>

    </div>

    {{-- Auto-scroll & New Message Detection --}}
    <script>
        document.addEventListener('livewire:load', function() {
            const container = document.getElementById('messagesContainer');

            const scrollToBottom = () => container.scrollTop = container.scrollHeight;

            scrollToBottom();

            Livewire.hook('message.processed', () => {
                scrollToBottom();
            });
        });
    </script>


</div>
