<?php

namespace App\Livewire\Units;

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

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

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

    #[Validate('required|string|max:10')]
    public string $symbol = '';

    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(Unit $unit): void
    {
        $this->unit = $unit;
        $this->name = (string) $unit->name;
        $this->symbol = (string) $unit->symbol;
        $this->description = $unit->description;
        $this->computeCanSave();
    }

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

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

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

        $this->success = false;
        $this->error = false;
        $this->successMessage = null;
        $this->errorMessage = null;

        $this->resetValidation();

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

            $data = [
                'name' => $this->name,
                'symbol' => $this->symbol,
                'description' => $this->description,
            ];

            if ($this->name !== $this->unit->name) {
                $data['slug'] = Unit::generateUniqueSlug($this->name);
            }

            $this->unit->update($data);

            $this->success = true;
            $this->successMessage = 'Unité modifiée avec 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.units.edit');
    }
}
