<?php

namespace App\Livewire\SaleTypes;

use App\Models\SaleType;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class Edit extends Component
{
    public SaleType $saleType;

    #[Validate('required|string|min:2')]
    public string $name = '';

    public ?string $description = null;

    public bool $loading = false;

    public bool $can_save = false;

    public bool $success = false;

    public bool $error = false;

    public ?string $successMessage = null;

    public ?string $errorMessage = null;

    public function mount(SaleType $saleType): void
    {
        $this->saleType = $saleType;
        $this->name = (string) $saleType->name;
        $this->description = $saleType->description;
        $this->computeCanSave();
    }

    public function computeCanSave(): void
    {
        $this->can_save = strlen($this->name) >= 2 && ! $this->loading;
    }

    public function updated($propertyName): void
    {
        $this->validateOnly($propertyName);
        $this->computeCanSave();
    }

    public function save(): void
    {
        $this->loading = true;
        $this->computeCanSave();

        // Reset previous messages
        $this->success = false;
        $this->error = false;
        $this->successMessage = null;
        $this->errorMessage = null;

        // Clear previous validation errors
        $this->resetValidation();

        try {
            $this->validate([
                'name' => ['required', 'string', 'min:2'],
                'description' => ['nullable', 'string'],
            ]);

            $this->saleType->update([
                'name' => $this->name,
                'description' => $this->description,
            ]);

            $this->success = true;
            $this->successMessage = 'Succès';

        } catch (\Illuminate\Validation\ValidationException $e) {
            $this->error = true;
            $this->errorMessage = 'Erreur de validation. Veuillez vérifier les champs.';
            throw $e;
        } catch (\Exception $e) {
            $this->error = true;
            $this->errorMessage = 'Erreur lors de la sauvegarde: '.$e->getMessage();
        } finally {
            $this->loading = false;
            $this->computeCanSave();
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.sale-types.edit');
    }
}
