<?php

namespace App\Livewire\Users;

use App\Models\User;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

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

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

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

    #[Validate('nullable|string|min:6')]
    public ?string $email = null;

    #[Validate('nullable|string|min:6')]
    public ?string $phone = null;

    public string $role = '';

    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(User $user): void
    {
        $this->user = $user;
        $this->firstname = (string) $user->firstname;
        $this->lastname = (string) $user->lastname;
        $this->email = (string) $user->email;
        $this->phone = $user->phone ?? null;
        $this->role = $user->role;
        $this->computeCanSave();
    }

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

    public function updated($propertyName): void
    {
        // Skip validation for role since it has complex rules
        if ($propertyName !== 'role') {
            $this->validateOnly($propertyName);
        }
        $this->computeCanSave();
    }

    public function save(): void
    {
        $this->loading = true;
        $this->computeCanSave(); // Update can_save immediately
        
        // Reset previous messages
        $this->success = false;
        $this->error = false;
        $this->successMessage = null;
        $this->errorMessage = null;
        
        // Clear previous validation errors
        $this->resetValidation();

        try {
            $this->validate([
                'firstname' => ['required', 'string', 'min:2'],
                'lastname' => ['required', 'string', 'min:2'],
                'phone' => ['nullable', 'string', 'min:6', Rule::unique('users', 'phone')->ignore($this->user->id)],
                'role' => ['required', 'string', Rule::in(array_column(User::ROLES, 'slug'))],
            ]);

            $this->user->update([
                'firstname' => $this->firstname,
                'lastname' => $this->lastname,
                'phone' => $this->phone,
                'role' => $this->role,
            ]);

            $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; // Re-throw to show field-specific errors
        } 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.users.edit');
    }
}


