<?php

namespace App\Filament\Pages;

use App\Exceptions\LogisticsApiException;
use App\Services\LogisticsService;
use App\Support\ApiErrorTranslator;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;

class Journaux extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedBookOpen;

    protected static ?string $navigationLabel = 'Journaux';

    protected static ?string $title = 'Journaux';

    protected static ?int $navigationSort = 4;

    protected string $view = 'filament.pages.journaux';

    public string $mode = 'read';

    public string $select = '';

    public int $results = 30;

    public string $type = '';

    public array $data = [];

    public ?array $metadata = null;

    public ?string $errorMessage = null;

    public bool $hasSearched = false;

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableJnlList(): array
    {
        return [
            ['name' => 'TYPE', 'type' => 'string', 'required' => 'Oui', 'description' => 'Code de type de journal (1 ou 2 caracteres). Ex: C=Client, S=Fournisseur, K=Stock, CI=Facture client, CO=Commande.'],
            ['name' => 'select', 'type' => 'string', 'required' => 'Non', 'description' => 'Colonnes a retourner, separees par des virgules (colonnes de la table jnl). Si omis, seule la colonne jnl est retournee.'],
            ['name' => 'results', 'type' => 'string', 'required' => 'Non', 'description' => 'Nombre maximum de resultats. Doit etre au format string. Limite par defaut : 30.'],
        ];
    }

    public function searchJournaux(): void
    {
        $this->errorMessage = null;

        if (blank($this->type)) {
            $this->errorMessage = 'Le champ type de journal (TYPE) est obligatoire.';

            return;
        }

        $this->hasSearched = true;

        try {
            $service = app(LogisticsService::class);

            $params = array_filter([
                'select' => $this->select,
                'results' => (string) $this->results,
                'TYPE' => $this->type,
            ]);

            $response = $service->jnlList($params);

            $this->data = $response['data'] ?? [];
            $this->metadata = $response['metadata'] ?? null;
            $this->errorMessage = ApiErrorTranslator::translate($response['error'] ?? null);
        } catch (LogisticsApiException $e) {
            $this->errorMessage = ApiErrorTranslator::translate($e->getMessage());
            $this->data = [];
        } catch (\Throwable $e) {
            $this->errorMessage = ApiErrorTranslator::translate($e->getMessage());
            $this->data = [];
        }
    }
}
