<?php

namespace App\Livewire\Prescriptions;

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

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

    public ?array $prescription = null;

    public ?Prescription $prescriptionObj = null;

    public bool $offlineMode = false;

    public ?string $errorMessage = null;

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

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

        // First, try to get from local database
        $this->prescriptionObj = Prescription::where('reference', $this->reference)->first();

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

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

            if ($apiData) {
                $this->prescription = $apiData;

                // Sync to local database
                \syncPrescriptionToLocal($apiData);
                $this->prescriptionObj = Prescription::where('reference', $this->reference)->first();
            }

            $this->offlineMode = false;
        } else {
            // Check if it's a connection error
            $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 prescription pour le moment.';
            }

            // If offline and we have local data, use it
            if ($this->offlineMode && $this->prescriptionObj) {
                $this->prescription = [
                    'reference' => $this->prescriptionObj->reference,
                    'customer_name' => $this->prescriptionObj->customer_name,
                    'status' => $this->prescriptionObj->status,
                    'products' => $this->prescriptionObj->products ?? [],
                    'notes' => $this->prescriptionObj->notes,
                    'created_at' => $this->prescriptionObj->created_at?->toIso8601String(),
                ];
            }
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.prescriptions.show', [
            'prescription' => $this->prescription,
            'prescriptionObj' => $this->prescriptionObj,
            'reference' => $this->reference,
            'offlineMode' => $this->offlineMode,
            'errorMessage' => $this->errorMessage,
        ]);
    }
}
