<?php

namespace App\Livewire\Auth;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Livewire\Component;

class SetPassword extends Component
{
    public User $user;

    public string $password = '';

    public string $password_confirmation = '';

    public bool $loading = false;

    public bool $success = false;

    public ?string $errorMessage = null;

    public function mount(User $user): void
    {
        $this->user = $user;
    }

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

        $this->validate([
            'password' => ['required', Password::defaults()],
            'password_confirmation' => ['required', 'same:password'],
        ], [
            'password.required' => 'Le mot de passe est requis.',
            'password_confirmation.required' => 'La confirmation du mot de passe est requise.',
            'password_confirmation.same' => 'La confirmation du mot de passe ne correspond pas.',
        ]);

        try {
            $this->user->update([
                'password' => Hash::make($this->password),
            ]);

            $this->success = true;
            $this->loading = false;

            session()->flash('success', 'Votre mot de passe a été défini avec succès. Vous pouvez maintenant vous connecter.');

            // Redirect to login after a short delay
            $this->redirectRoute('login', navigate: true);

        } catch (\Exception $e) {
            $this->errorMessage = 'Erreur lors de la définition du mot de passe. Veuillez réessayer.';
            $this->loading = false;
        }
    }

    public function render()
    {
        return view('livewire.auth.set-password');
    }
}
