<?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 Tiers extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;

    protected static ?string $navigationLabel = 'Tiers';

    protected static ?string $title = 'Tiers';

    protected static ?int $navigationSort = 5;

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

    public string $mode = 'read';

    public string $select = 'custid,name';

    public string $search = '';

    public int $results = 10;

    public string $historyThirdId = '';

    public array $data = [];

    public array $historyData = [];

    public ?array $metadata = null;

    public ?string $errorMessage = null;

    public bool $hasSearched = false;

    public bool $hasHistory = false;

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableThirdList(): array
    {
        return [
            ['name' => 'search', 'type' => 'string', 'required' => 'Oui', 'description' => 'Filtre de recherche textuel. Recherche dans name, groupid et vat (pas dans custid). Obligatoire.'],
            ['name' => 'select', 'type' => 'string', 'required' => 'Non', 'description' => 'Colonnes a retourner, separees par des virgules. Par defaut : custid, name.'],
            ['name' => 'results', 'type' => 'int', 'required' => 'Non', 'description' => "Sans effet. L'API retourne toujours un maximum de 10 resultats."],
        ];
    }

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableArtHistory(): array
    {
        return [
            ['name' => 'thirdid', 'type' => 'string', 'required' => 'Oui', 'description' => 'Identifiant du tiers (custid de la table cust). Sensible a la casse : doit etre en minuscules (thirdid, pas THIRDID).'],
        ];
    }

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

        if (blank($this->search)) {
            $this->errorMessage = 'Le champ de recherche (search) est obligatoire.';

            return;
        }

        $this->hasSearched = true;

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

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

            $response = $service->thirdList($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 = [];
        }
    }

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

        if (blank($this->historyThirdId)) {
            $this->errorMessage = 'Le champ identifiant tiers (thirdid) est obligatoire.';

            return;
        }

        $this->hasHistory = true;

        try {
            $service = app(LogisticsService::class);
            $response = $service->thirdGetArtHistory($this->historyThirdId);

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