<?php

namespace App\Livewire\Conversations;

use App\Models\Conversation;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class Show extends Component
{
    public string $slug;

    public ?array $conversation = null;

    public ?Conversation $conversationObj = null;

    public array $messages = [];

    public bool $offlineMode = false;

    public ?string $errorMessage = null;

    public string $clientName = '';

    public function mount(string $slug): void
    {
        $this->slug = $slug;
        $this->loadConversation();
    }

    public function loadConversation(): void
    {
        $this->errorMessage = null;
        $this->offlineMode = false;

        // Try to get from local database
        $this->conversationObj = Conversation::where('slug', $this->slug)->first();

        // Try to get from API
        $response = \getApiSingleConversation($this->slug);

        if ($response['success'] ?? false) {
            $apiData = $response['data'] ?? null;

            if ($apiData) {
                $this->conversation = $apiData;
                $this->messages = $apiData['messages'] ?? [];
                $this->clientName = $apiData['client_name'] ?? 
                    trim(($apiData['user']['first_name'] ?? '').' '.($apiData['user']['last_name'] ?? '')) ?: 
                    'Client inconnu';

                // Sync to local database
                \syncConversationToLocal($apiData);
                $this->conversationObj = Conversation::where('slug', $this->slug)->first();
            }

            $this->offlineMode = false;
        } else {
            $status = $response['status'] ?? null;
            $this->offlineMode = ($status === 0 || $status === null);

            if ($this->offlineMode) {
                $this->errorMessage = 'Impossible de se connecter au serveur. Vérifiez votre connexion internet.';
            } else {
                $this->errorMessage = $response['message'] ?? 'Impossible de récupérer la conversation pour le moment.';
            }

            // If offline and we have local data, use it
            if ($this->offlineMode && $this->conversationObj) {
                $this->clientName = $this->conversationObj->client_full_name;
                $this->messages = $this->conversationObj->messages->map(function ($msg) {
                    return [
                        'body' => $msg->body,
                        'sender_type' => $msg->sender_type,
                        'created_at' => $msg->api_created_at?->toIso8601String(),
                    ];
                })->toArray();
            }
        }
    }

    public function refreshConversation(): void
    {
        $this->loadConversation();
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.conversations.show', [
            'conversation' => $this->conversation,
            'messages' => $this->messages,
            'clientName' => $this->clientName,
            'offlineMode' => $this->offlineMode,
            'errorMessage' => $this->errorMessage,
        ]);
    }
}
