<?php

namespace App\Livewire\Forms;

use App\Models\User;
use Illuminate\Validation\Rule;
use Livewire\Form;

class UserForm extends Form
{
    public string $document = '';

    public string $name = '';

    public string $paternal_surname = '';

    public string $maternal_surname = '';

    public string $email = '';

    public string $phone = '';

    public string $password = '';

    public string $password_confirmation = '';

    public bool $status = true;

    /** @var list<int> */
    public array $roleIds = [];

    /**
     * @return array<string, mixed>
     */
    public function rules(bool $isEditing, ?int $ignoreUserId = null): array
    {
        return [
            'document' => [
                'required',
                'string',
                'max:20',
                Rule::unique('users', 'document')->ignore($ignoreUserId),
            ],
            'name' => ['required', 'string', 'max:100'],
            'paternal_surname' => ['required', 'string', 'max:100'],
            'maternal_surname' => ['required', 'string', 'max:100'],
            'email' => [
                'required',
                'email',
                'max:255',
                Rule::unique('users', 'email')->ignore($ignoreUserId),
            ],
            'phone' => ['nullable', 'string', 'max:20'],
            'password' => array_values(array_filter([
                $isEditing ? 'nullable' : 'required',
                'string',
                'min:8',
                'confirmed',
            ])),
            'status' => ['boolean'],
            'roleIds' => ['required', 'array', 'min:1'],
            'roleIds.*' => ['integer', 'exists:roles,id'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function validationMessages(): array
    {
        return [
            'document.required' => 'El documento es obligatorio.',
            'document.unique' => 'Ya existe un usuario con este documento.',
            'name.required' => 'Los nombres son obligatorios.',
            'paternal_surname.required' => 'El apellido paterno es obligatorio.',
            'maternal_surname.required' => 'El apellido materno es obligatorio.',
            'email.required' => 'El correo es obligatorio.',
            'email.email' => 'Ingrese un correo válido.',
            'email.unique' => 'Ya existe un usuario con este correo.',
            'password.required' => 'La contraseña es obligatoria.',
            'password.min' => 'La contraseña debe tener al menos :min caracteres.',
            'password.confirmed' => 'La confirmación de contraseña no coincide.',
            'roleIds.required' => 'Seleccione al menos un rol.',
            'roleIds.min' => 'Seleccione al menos un rol.',
            'roleIds.*.exists' => 'Uno de los roles seleccionados no es válido.',
        ];
    }

    public function resetForCreate(): void
    {
        $this->document = '';
        $this->name = '';
        $this->paternal_surname = '';
        $this->maternal_surname = '';
        $this->email = '';
        $this->phone = '';
        $this->password = '';
        $this->password_confirmation = '';
        $this->status = true;
        $this->roleIds = [];
    }

    public function fillFromUser(User $user): void
    {
        $this->document = $user->document;
        $this->name = $user->name;
        $this->paternal_surname = $user->paternal_surname;
        $this->maternal_surname = $user->maternal_surname;
        $this->email = $user->email;
        $this->phone = (string) ($user->phone ?? '');
        $this->password = '';
        $this->password_confirmation = '';
        $this->status = (bool) $user->status;
        $this->roleIds = $user->roles->pluck('id')->map(fn (int|string $id) => (int) $id)->values()->all();
    }
}
