<?php

namespace App\Livewire\Account;

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

#[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 = '';

    /**
     * Displayed but not editable.
     */
    public string $username = '';

    public ?string $phone = null;

    public ?string $email = null;

    public bool $can_save = false;

    public bool $loading = false;

    public bool $success = false;
    public bool $error = false;
    public ?string $successMessage = null;
    public ?string $errorMessage = null;

    public function mount(): void
    {
        $this->user = Auth::user();
        $this->firstname = (string) $this->user->firstname;
        $this->lastname = (string) $this->user->lastname;
        $this->username = (string) $this->user->username;
        $this->phone = $this->user->phone;
        $this->email = $this->user->email;
        $this->computeCanSave();
    }

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

        $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)],
        ]);

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

            $this->successMessage = 'Profil mis à jour.';
            $this->success = true;
        } catch (\Throwable $e) {
            $this->errorMessage = 'Échec de la mise à jour du profil.';
            $this->error = true;
        } finally {
            $this->loading = false;
            $this->computeCanSave();
        }
    }

    public function updatedFirstname(): void { $this->computeCanSave(); }
    public function updatedLastname(): void { $this->computeCanSave(); }
    public function updatedPhone(): void { $this->computeCanSave(); }

    private function computeCanSave(): void
    {
        $firstnameOk = is_string($this->firstname) && mb_strlen(trim($this->firstname)) >= 2;
        $lastnameOk = is_string($this->lastname) && mb_strlen(trim($this->lastname)) >= 2;
        $this->can_save = $firstnameOk && $lastnameOk;
    }

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


