<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Hash;

return new class extends Component
{
    use WithFileUploads;

    public User $user;

    public string $name = '';
    public string $email = '';
    public string $role = '';
    public string $password = '';
    public string $password_confirmation = '';
    public $avatar = null;

    public function mount(User $user): void
    {
        $this->user  = $user;
        $this->name  = $user->name;
        $this->email = $user->email;
        $this->role  = $user->roles->first()?->name ?? '';
    }

    public function save(): void
    {
        $this->validate([
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'email', 'max:255', 'unique:users,email,' . $this->user->id],
            'role'     => ['required', 'string', 'exists:roles,name'],
            'password' => ['nullable', 'confirmed', Password::min(8)],
            'avatar'   => ['nullable', 'image', 'max:2048'],
        ]);

        // Prevent removing superadmin role from the only superadmin
        if ($this->user->hasRole('superadmin') && $this->role !== 'superadmin') {
            $superadminCount = User::role('superadmin')->count();
            if ($superadminCount <= 1) {
                $this->addError('role', 'Cannot remove the last superadmin role.');
                return;
            }
        }

        $data = [
            'name'  => $this->name,
            'email' => $this->email,
        ];

        if ($this->avatar) {
            $data['avatar'] = $this->avatar->store('avatars', 'public');
        }

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

        $this->user->update($data);
        $this->user->syncRoles([$this->role]);

        session()->flash('success', 'User updated successfully.');
        $this->redirect(route('admin.users'), navigate: true);
    }

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function with(): array
    {
        return [
            'roles' => Role::orderBy('name')->pluck('name'),
        ];
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/90b9c4c2.blade.php', $data);
    }
};
