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

    protected static ?string $navigationLabel = 'Divers';

    protected static ?string $title = 'Divers';

    protected static ?int $navigationSort = 6;

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

    public string $mode = 'read';

    // getserialnumber
    public array $serialData = [];

    // codes_list
    public string $code = '';

    public string $codesSelect = '';

    public array $codesData = [];

    // custom_geninv_updatestock
    public string $stkArtId = '';

    public string $stkId = '';

    public string $stkQty = '';

    public string $stkToCheck = '';

    public string $stkToCheckDetail = '';

    public string $stkMode = '1';

    public string $stkThirdId = '';

    public array $updateStockResult = [];

    public ?string $errorMessage = null;

    // Tracking
    public bool $hasSerial = false;

    public bool $hasCodes = false;

    public bool $hasUpdatedStock = false;

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableCodesList(): array
    {
        return [
            ['name' => 'code', 'type' => 'string', 'required' => 'Oui', 'description' => 'Nom exact du groupe de codes internes (table incodes). Correspondance exacte, sensible a la casse (MAJUSCULES). Chaine vide pour la liste maitre.'],
            ['name' => 'select', 'type' => 'string', 'required' => 'Non', 'description' => 'Sans effet. Toutes les colonnes sont toujours retournees.'],
        ];
    }

    /**
     * @return array<int, array{name: string, type: string, required: string, description: string}>
     */
    public function paramTableUpdateStock(): array
    {
        return [
            ['name' => 'ARTID', 'type' => 'string', 'required' => 'Oui', 'description' => 'Identifiant de l\'article (champ artid de la table art).'],
            ['name' => 'STKID', 'type' => 'string', 'required' => 'Oui', 'description' => 'Code du depot / entrepot. Valeurs via codes_list STOCK (ex: A, SG).'],
            ['name' => 'QTY', 'type' => 'string', 'required' => 'Oui', 'description' => 'Quantite a ajouter au stock. Peut etre negatif pour retirer du stock.'],
            ['name' => 'MODE', 'type' => 'string', 'required' => 'Oui', 'description' => '"0" = Inventaire (journal KI). "1" = Restock (journal KM, necessite THIRDID).'],
            ['name' => 'THIRDID', 'type' => 'string', 'required' => 'Si MODE=1', 'description' => 'Identifiant du tiers / fournisseur (custid de la table cust). Obligatoire en mode Restock.'],
            ['name' => 'TOCHECK', 'type' => 'string', 'required' => 'Oui', 'description' => 'Prix de controle. Stocke avec le mouvement mais n\'affecte pas la quantite de stock.'],
            ['name' => 'TOCHECKDETAIL', 'type' => 'string', 'required' => 'Oui', 'description' => 'Remarque / detail de controle. Texte libre stocke avec le mouvement.'],
        ];
    }

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

        try {
            $service = app(LogisticsService::class);
            $response = $service->getSerialNumber();

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

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

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

            return;
        }

        $this->hasCodes = true;

        try {
            $service = app(LogisticsService::class);
            $params = ['code' => $this->code];

            if (filled($this->codesSelect)) {
                $params['select'] = $this->codesSelect;
            }

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

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

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

        if (blank($this->stkArtId) || blank($this->stkId) || blank($this->stkQty) || blank($this->stkMode)) {
            $this->errorMessage = 'Les champs ARTID, STKID, QTY et MODE sont obligatoires.';

            return;
        }

        if ($this->stkMode === '1' && blank($this->stkThirdId)) {
            $this->errorMessage = 'Le champ THIRDID est obligatoire en mode Restock (MODE=1).';

            return;
        }

        $this->hasUpdatedStock = true;

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

            $params = [
                'ARTID' => $this->stkArtId,
                'STKID' => $this->stkId,
                'QTY' => $this->stkQty,
                'TOCHECK' => $this->stkToCheck,
                'TOCHECKDETAIL' => $this->stkToCheckDetail,
                'MODE' => $this->stkMode,
            ];

            if (filled($this->stkThirdId)) {
                $params['THIRDID'] = $this->stkThirdId;
            }

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

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