<?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 = '';

    // third_add
    public string $addName = '';

    public string $addVat = '';

    public string $addEmail = '';

    // third_mod
    public string $modCustId = '';

    public string $modName = '';

    public string $modVat = '';

    public string $modEmail = '';

    public array $data = [];

    public array $historyData = [];

    public array $addResult = [];

    public array $modResult = [];

    public ?array $metadata = null;

    public ?string $errorMessage = null;

    public bool $hasSearched = false;

    public bool $hasHistory = false;

    public bool $hasAdded = false;

    public bool $hasModified = 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).'],
        ];
    }

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableThirdAdd(): array
    {
        return [
            ['name' => 'NAME', 'type' => 'string', 'required' => 'Non', 'description' => 'Nom du tiers (raison sociale ou nom complet).'],
            ['name' => 'VAT', 'type' => 'string', 'required' => 'Non', 'description' => 'Numéro de TVA (ex : BE0123456789).'],
            ['name' => 'EMAIL', 'type' => 'string', 'required' => 'Non', 'description' => 'Adresse e-mail du tiers.'],
        ];
    }

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableThirdMod(): array
    {
        return [
            ['name' => 'CUSTID', 'type' => 'string', 'required' => 'Oui', 'description' => 'Identifiant du tiers à modifier (champ custid de la table cust). Doit exister.'],
            ['name' => 'NAME', 'type' => 'string', 'required' => 'Non', 'description' => 'Nouveau nom du tiers.'],
            ['name' => 'VAT', 'type' => 'string', 'required' => 'Non', 'description' => 'Nouveau numéro de TVA.'],
            ['name' => 'EMAIL', 'type' => 'string', 'required' => 'Non', 'description' => 'Nouvelle adresse e-mail.'],
        ];
    }

    public function addTiers(): void
    {
        $this->errorMessage = null;
        $this->hasAdded = true;

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

            $params = [];

            if (filled($this->addName)) {
                $params['NAME'] = $this->addName;
            }
            if (filled($this->addVat)) {
                $params['VAT'] = $this->addVat;
            }
            if (filled($this->addEmail)) {
                $params['EMAIL'] = $this->addEmail;
            }

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

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

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

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

            return;
        }

        $this->hasModified = true;

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

            $params = ['CUSTID' => $this->modCustId];

            if (filled($this->modName)) {
                $params['NAME'] = $this->modName;
            }
            if (filled($this->modVat)) {
                $params['VAT'] = $this->modVat;
            }
            if (filled($this->modEmail)) {
                $params['EMAIL'] = $this->modEmail;
            }

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

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

    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 = [];
        }
    }
}
