<?php

namespace App\Livewire\Prescriptions;

use Illuminate\Pagination\LengthAwarePaginator;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

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

    protected string $paginationTheme = 'tailwind';

    public array $prescriptionsPayload = [];

    public string $search = '';

    public string $status = '';

    public int $perPage = 15;

    public bool $loading = false;

    public ?string $errorMessage = null;

    public bool $offlineMode = false;

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

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

        $this->prescriptionsPayload = $this->serializePaginator($this->emptyPaginator());
        $this->loadPrescriptions();
    }

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

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

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

    public function updatedPage(): void
    {
        $this->loadPrescriptions();
    }

    public function refreshPrescriptions(): void
    {
        $this->loadPrescriptions();
    }

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

    protected function loadPrescriptions(): void
    {
        $this->loading = true;
        $this->errorMessage = null;
        $this->offlineMode = false;

        $currentPage = $this->getPage();

        $params = [
            'search' => $this->search !== '' ? $this->search : null,
            'status' => $this->status !== '' ? $this->status : null,
            'per_page' => $this->perPage,
            'page' => $currentPage,
        ];

        $response = \getApiPrescriptions($params);

        if ($response['success'] ?? false) {
            $apiData = $response['data'] ?? [];
            
            // Extract orders from API response
            $ordersList = $apiData['orders'] ?? $apiData['data'] ?? $apiData;
            
            // Handle different API response structures
            if (is_array($ordersList) && isset($ordersList['data'])) {
                // Laravel pagination structure
                $this->prescriptionsPayload = [
                    'data' => $ordersList['data'],
                    'total' => (int) ($ordersList['total'] ?? count($ordersList['data'])),
                    'per_page' => (int) ($ordersList['per_page'] ?? $this->perPage),
                    'current_page' => (int) ($ordersList['current_page'] ?? $currentPage),
                    'path' => request()->url(),
                ];
            } elseif (is_array($ordersList)) {
                // Simple array of orders
                $this->prescriptionsPayload = [
                    'data' => $ordersList,
                    'total' => count($ordersList),
                    'per_page' => $this->perPage,
                    'current_page' => $currentPage,
                    'path' => request()->url(),
                ];
            } else {
                $this->prescriptionsPayload = $this->serializePaginator($this->emptyPaginator());
            }
            
            $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 les prescriptions pour le moment.';
            }
            
            $this->prescriptionsPayload = $this->serializePaginator($this->emptyPaginator());
        }

        $this->loading = false;
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        $prescriptions = $this->hydratePaginatorFromPayload($this->prescriptionsPayload);

        $statusOptions = collect([
            (object) ['value' => '', 'label' => 'Tous'],
            (object) ['value' => 'En attente', 'label' => 'En attente'],
            (object) ['value' => 'Approuvé', 'label' => 'Approuvé'],
            (object) ['value' => 'Rejeté', 'label' => 'Rejeté'],
            (object) ['value' => 'Terminé', 'label' => 'Terminé'],
            (object) ['value' => 'Annulé', 'label' => 'Annulé'],
        ]);

        $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.prescriptions.index', [
            'prescriptions' => $prescriptions,
            'statusOptions' => $statusOptions,
            'perPageOptions' => $perPageOptions,
        ]);
    }

    protected function emptyPaginator(): LengthAwarePaginator
    {
        return new LengthAwarePaginator([], 0, $this->perPage, $this->getPage(), [
            'path' => request()->url(),
            'query' => request()->query(),
        ]);
    }

    protected function serializePaginator(LengthAwarePaginator $paginator): array
    {
        $array = $paginator->toArray();

        return [
            'data' => $array['data'] ?? [],
            'total' => $array['total'] ?? 0,
            'per_page' => (int) ($array['per_page'] ?? $paginator->perPage()),
            'current_page' => (int) ($array['current_page'] ?? $paginator->currentPage()),
            'path' => $paginator->path(),
        ];
    }

    protected function hydratePaginatorFromPayload(array $payload): LengthAwarePaginator
    {
        if (empty($payload)) {
            return $this->emptyPaginator();
        }

        return new LengthAwarePaginator(
            $payload['data'] ?? [],
            (int) ($payload['total'] ?? 0),
            (int) ($payload['per_page'] ?? $this->perPage),
            (int) ($payload['current_page'] ?? 1),
            [
                'path' => $payload['path'] ?? request()->url(),
                'query' => request()->query(),
            ]
        );
    }
}
