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

    protected static ?string $navigationLabel = 'Articles';

    protected static ?string $title = 'Articles';

    protected static ?int $navigationSort = 2;

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

    public string $mode = 'read';

    public string $search = '';

    public string $select = 'artid,name1';

    public string $barcode = '';

    public string $stockArticleId = '';

    // art_add
    public string $addArtId = '';

    public string $addName = '';

    public string $addSalePrice = '';

    // art_mod
    public string $modArtId = '';

    public string $modName = '';

    public string $modSalePrice = '';

    public array $data = [];

    public array $stockData = [];

    public array $addResult = [];

    public array $modResult = [];

    public ?array $metadata = null;

    public ?string $errorMessage = null;

    public bool $hasSearched = false;

    public bool $hasCheckedStock = false;

    public bool $hasAdded = false;

    public bool $hasModified = false;

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableArtList(): array
    {
        return [
            ['name' => 'search', 'type' => 'string', 'required' => 'Oui', 'description' => 'Filtre de recherche textuel. Recherche dans artid et name1. Obligatoire.'],
            ['name' => 'select', 'type' => 'string', 'required' => 'Non', 'description' => 'Colonnes a retourner, separees par des virgules (colonnes de la table art).'],
            ['name' => 'barcode', 'type' => 'string', 'required' => 'Non', 'description' => 'Sans effet observable. Le parametre search reste obligatoire meme si barcode est fourni.'],
        ];
    }

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableArtGetstk(): array
    {
        return [
            ['name' => 'ARTID', 'type' => 'string', 'required' => 'Oui', 'description' => "Identifiant unique de l'article (champ artid de la table art)."],
        ];
    }

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

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

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

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

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableArtAdd(): array
    {
        return [
            ['name' => 'ARTID', 'type' => 'string', 'required' => 'Oui', 'description' => "Identifiant unique de l'article à créer. Doit être unique dans la table art."],
            ['name' => 'NAME1', 'type' => 'string', 'required' => 'Non', 'description' => "Nom / libellé de l'article."],
            ['name' => 'SALEPRICE', 'type' => 'string', 'required' => 'Non', 'description' => 'Prix de vente unitaire (format string, ex : "99.99").'],
        ];
    }

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableArtMod(): array
    {
        return [
            ['name' => 'ARTID', 'type' => 'string', 'required' => 'Oui', 'description' => "Identifiant de l'article à modifier. Doit exister dans la table art."],
            ['name' => 'NAME1', 'type' => 'string', 'required' => 'Non', 'description' => "Nouveau nom / libellé de l'article."],
            ['name' => 'SALEPRICE', 'type' => 'string', 'required' => 'Non', 'description' => 'Nouveau prix de vente unitaire (format string).'],
        ];
    }

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

        if (blank($this->addArtId)) {
            $this->errorMessage = 'Le champ identifiant article (ARTID) est obligatoire.';

            return;
        }

        $this->hasAdded = true;

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

            $params = ['ARTID' => $this->addArtId];

            if (filled($this->addName)) {
                $params['NAME1'] = $this->addName;
            }
            if (filled($this->addSalePrice)) {
                $params['SALEPRICE'] = $this->addSalePrice;
            }

            $response = $service->artAdd($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 modArticle(): void
    {
        $this->errorMessage = null;

        if (blank($this->modArtId)) {
            $this->errorMessage = 'Le champ identifiant article (ARTID) est obligatoire.';

            return;
        }

        $this->hasModified = true;

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

            $params = ['ARTID' => $this->modArtId];

            if (filled($this->modName)) {
                $params['NAME1'] = $this->modName;
            }
            if (filled($this->modSalePrice)) {
                $params['SALEPRICE'] = $this->modSalePrice;
            }

            $response = $service->artMod($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 getStock(): void
    {
        $this->errorMessage = null;

        if (blank($this->stockArticleId)) {
            $this->errorMessage = 'Le champ identifiant article (ARTID) est obligatoire pour verifier le stock.';

            return;
        }

        $this->hasCheckedStock = true;

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

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