<?php

namespace App\Components\Contact;

use App\Models\Contact\Hub\ContactMessage;
use Illuminate\Database\Eloquent\Model;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;

class CommunicationTimeline extends Component
{
    use WithPagination;

    public Model $model;

    public ?string $filterChannel = null;
    public ?string $filterStatus = null;

    /** When true, show inbound messages (institution responses) as well as outbound. */
    public bool $includeInbound = false;

    /** ID of the message currently open in the preview modal. */
    public ?int $openMessageId = null;

    protected string $paginationTheme = 'bootstrap';

    public function mount(Model $model): void
    {
        $this->model = $model;
    }

    #[On('contactMessageQueued')]
    #[On('contactMessageSent')]
    public function refresh(): void
    {
        $this->resetPage();
    }

    public function openMessage(int $id): void
    {
        $this->openMessageId = $id;
        $this->dispatch('ct-open-modal');
    }

    public function closeMessage(): void
    {
        $this->openMessageId = null;
    }

    public function render()
    {
        $messages = ContactMessage::query()
            ->forMessageable($this->model)
            ->when(!$this->includeInbound, fn ($q) => $q->outbound())
            ->when($this->filterChannel, fn ($q) => $q->where('channel', $this->filterChannel))
            ->when($this->filterStatus, fn ($q) => $q->where('status', $this->filterStatus))
            ->with(['template', 'creator', 'senderEmail', 'smsSender'])
            ->recent()
            ->paginate(10);

        $openMessage = $this->openMessageId
            ? ContactMessage::with(['attachments', 'template', 'creator', 'senderEmail', 'events'])
                ->find($this->openMessageId)
            : null;

        return view('components.contact.communication-timeline', compact('messages', 'openMessage'));
    }
}
