<?php

namespace App\Livewire\Users;

use App\Domain\Identity\Models\Person;
use App\Domain\Identity\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إدارة المستخدم')]
class UserForm extends Component
{
    public ?User $user = null;
    public bool $editing = false;

    public string $name = '';
    public string $name_ar = '';
    public string $email = '';
    public string $password = '';
    public string $password_confirmation = '';
    public ?int $role_id = null;
    public ?int $person_id = null;
    public string $status = 'active';

    public function mount(?User $user = null): void
    {
        if ($user && $user->exists) {
            $this->user = $user;
            $this->editing = true;
            $this->name = $user->name;
            $this->name_ar = $user->name_ar ?? '';
            $this->email = $user->email;
            $this->role_id = $user->role_id;
            $this->person_id = $user->person_id;
            $this->status = $user->status ?? 'active';
        }
    }

    public function rules(): array
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($this->user?->id)],
            'role_id' => 'nullable|exists:roles,id',
            'person_id' => 'nullable|exists:people,id',
            'status' => 'required|in:active,inactive,suspended,pending',
        ];

        if (!$this->editing) {
            $rules['password'] = 'required|string|min:8|confirmed';
        } else {
            $rules['password'] = 'nullable|string|min:8|confirmed';
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'name.required' => 'الاسم بالإنجليزية مطلوب',
            'name_ar.required' => 'الاسم بالعربية مطلوب',
            'email.required' => 'البريد الإلكتروني مطلوب',
            'email.email' => 'صيغة البريد الإلكتروني غير صحيحة',
            'email.unique' => 'البريد الإلكتروني مستخدم بالفعل',
            'password.required' => 'كلمة المرور مطلوبة',
            'password.min' => 'كلمة المرور يجب أن تكون 8 أحرف على الأقل',
            'password.confirmed' => 'تأكيد كلمة المرور غير متطابق',
        ];
    }

    public function save(): void
    {
        $this->validate();

        $data = [
            'name' => $this->name,
            'name_ar' => $this->name_ar,
            'email' => $this->email,
            'role_id' => $this->role_id,
            'person_id' => $this->person_id,
            'status' => $this->status,
        ];

        if ($this->password) {
            $data['password'] = Hash::make($this->password);
        }

        if ($this->editing) {
            $this->user->update($data);
            session()->flash('success', 'تم تحديث المستخدم بنجاح');
        } else {
            $data['academy_id'] = app('current_academy')->id;
            User::create($data);
            session()->flash('success', 'تم إنشاء المستخدم بنجاح');
        }

        $this->redirect(route('users.list'), navigate: true);
    }

    public function render()
    {
        return view('livewire.users.user-form', [
            'roles' => Role::orderBy('level', 'desc')->get(['id', 'name_ar', 'slug']),
            'people' => Person::orderBy('name_ar')
                ->get(['id', 'name_ar'])
                ->map(fn ($p) => ['id' => $p->id, 'name' => $p->name_ar]),
        ]);
    }
}
