<?php

namespace App\Livewire\Conversations;

use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.dashboard')]
class Index extends Component
{
    use WithPagination;

    protected string $paginationTheme = 'tailwind';

    public string $search = '';

    public int $perPage = 15;

    public bool $loading = false;

    public ?string $errorMessage = null;

    public bool $offlineMode = false;

    protected $queryString = [
        'search' => ['except' => ''],
        'perPage' => ['except' => 15],
        'page' => ['except' => 1],
    ];

    public function mount(): void
    {
        $this->search = request()->query('search', $this->search);
        $this->perPage = (int) request()->query('per_page', $this->perPage) ?: $this->perPage;
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedPerPage(): void
    {
        $this->resetPage();
    }

    public function refreshConversations(): void
    {
        $this->resetPage();
    }

    public function resetFilters(): void
    {
        $this->search = '';
        $this->resetPage();
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        $this->loading = true;
        $this->errorMessage = null;
        $this->offlineMode = false;

        $params = [
            'search' => $this->search !== '' ? $this->search : null,
            'per_page' => $this->perPage,
            'page' => $this->getPage(),
        ];

        $response = \getAndSyncConversations($params);

        if ($response['success'] ?? false) {
            $conversations = $response['data'] ?? new \Illuminate\Pagination\LengthAwarePaginator([], 0, $this->perPage, 1);
            $this->offlineMode = false;
        } else {
            $status = $response['status'] ?? null;
            $this->offlineMode = ($status === 0 || $status === null);
            $this->errorMessage = $response['message'] ?? 'Impossible de récupérer les conversations pour le moment.';
            $conversations = new \Illuminate\Pagination\LengthAwarePaginator([], 0, $this->perPage, 1, [
                'path' => request()->url(),
                'query' => request()->query(),
            ]);
        }

        $this->loading = false;

        $perPageOptions = collect([
            (object) ['value' => 10, 'label' => '10 / page'],
            (object) ['value' => 15, 'label' => '15 / page'],
            (object) ['value' => 25, 'label' => '25 / page'],
            (object) ['value' => 50, 'label' => '50 / page'],
        ]);

        return view('livewire.conversations.index', [
            'conversations' => $conversations,
            'perPageOptions' => $perPageOptions,
        ]);
    }
}
