<?php

namespace App\Livewire\Expenses;

use App\Models\Expense;
use App\Models\ExpenseCategory;
use Livewire\Attributes\Layout;
use Livewire\Component;

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

    // Form properties
    public string $title = '';

    public ?string $description = null;

    public ?int $expense_category_id = null;

    public float $amount = 0;

    public ?string $expense_date = null;

    // UI properties
    public bool $loading = false;

    public bool $success = false;

    public bool $error = false;

    public ?string $successMessage = null;

    public ?string $errorMessage = null;

    // Options
    public array $categories = [];

    public function mount(Expense $expense): void
    {
        $this->expense = $expense->load(['category', 'user']);

        // Populate form
        $this->title = $expense->title;
        $this->description = $expense->description;
        $this->expense_category_id = $expense->expense_category_id;
        $this->amount = $expense->amount;
        $this->expense_date = $expense->expense_date?->format('Y-m-d');

        $this->loadCategories();
    }

    public function loadCategories(): void
    {
        $this->categories = ExpenseCategory::active()
            ->orderBy('name')
            ->get()
            ->map(fn ($category) => ['id' => $category->id, 'name' => $category->name])
            ->toArray();
    }

    public function rules()
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:1000'],
            'expense_category_id' => ['required', 'exists:expense_categories,id'],
            'amount' => ['required', 'numeric', 'min:0.01'],
            'expense_date' => ['required', 'date'],
        ];
    }

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

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

        $this->resetValidation();

        try {
            $this->validate([
                'title' => ['required', 'string', 'max:255'],
                'description' => ['nullable', 'string', 'max:1000'],
                'expense_category_id' => ['required', 'exists:expense_categories,id'],
                'amount' => ['required', 'numeric', 'min:0.01'],
                'expense_date' => ['required', 'date'],
            ]);

            $this->expense->update([
                'title' => $this->title,
                'description' => $this->description,
                'expense_category_id' => $this->expense_category_id,
                'amount' => $this->amount,
                'expense_date' => $this->expense_date,
            ]);

            $this->success = true;
            $this->successMessage = 'Dépense 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;
        }
    }

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