<?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;

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'),
        ];
    }
};
?>

<div>
    <header class="flex justify-between items-center mb-8">
        <div>
            <h1 class="text-2xl font-semibold tracking-tight text-gray-900">Edit User</h1>
            <p class="text-sm text-gray-500 mt-1">Update account details and role for {{ $user->name }}.</p>
        </div>
        <a href="{{ route('admin.users') }}" wire:navigate class="btn-secondary">← Back</a>
    </header>

    @if(session('success'))
        <div class="mb-6 px-4 py-3 bg-green-50 border border-green-200 text-green-700 text-sm rounded-md">{{ session('success') }}</div>
    @endif

    <form wire:submit="save" class="max-w-2xl space-y-6">

        <!-- Avatar -->
        <div class="card p-6">
            <h2 class="text-sm font-semibold text-gray-700 mb-4">Profile Photo</h2>
            <div class="flex items-center gap-5">
                <div class="w-16 h-16 rounded-full bg-gray-100 border border-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0">
                    @if($avatar)
                        <img src="{{ $avatar->temporaryUrl() }}" class="w-full h-full object-cover">
                    @elseif($user->avatar)
                        <img src="{{ asset('storage/' . $user->avatar) }}" class="w-full h-full object-cover">
                    @else
                        <span class="text-gray-400 text-xl font-bold">{{ strtoupper(substr($user->name, 0, 1)) }}</span>
                    @endif
                </div>
                <div>
                    <input wire:model="avatar" type="file" accept="image/*" class="text-sm text-gray-600">
                    <p class="text-xs text-gray-400 mt-1">Upload a new photo to replace the current one. Optional.</p>
                </div>
            </div>
            @error('avatar') <p class="text-red-500 text-xs mt-2">{{ $message }}</p> @enderror
        </div>

        <!-- Account Details -->
        <div class="card p-6 space-y-4">
            <h2 class="text-sm font-semibold text-gray-700 mb-2">Account Details</h2>

            <div>
                <label class="label">Full Name</label>
                <input wire:model="name" type="text" class="input-field w-full">
                @error('name') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
            </div>

            <div>
                <label class="label">Email Address</label>
                <input wire:model="email" type="email" class="input-field w-full">
                @error('email') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
            </div>

            <div>
                <label class="label">Role</label>
                <select wire:model="role" class="input-field w-full"
                    @if($user->id === auth()->id()) disabled @endif>
                    @foreach($roles as $r)
                        <option value="{{ $r }}">{{ ucfirst($r) }}</option>
                    @endforeach
                </select>
                @if($user->id === auth()->id())
                    <p class="text-xs text-gray-400 mt-1">You cannot change your own role.</p>
                @endif
                @error('role') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
            </div>
        </div>

        <!-- Change Password -->
        <div class="card p-6 space-y-4">
            <h2 class="text-sm font-semibold text-gray-700 mb-2">Change Password <span class="text-gray-400 font-normal">(leave blank to keep current)</span></h2>

            <div>
                <label class="label">New Password</label>
                <input wire:model="password" type="password" class="input-field w-full" placeholder="Min. 8 characters">
                @error('password') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
            </div>

            <div>
                <label class="label">Confirm New Password</label>
                <input wire:model="password_confirmation" type="password" class="input-field w-full">
            </div>
        </div>

        <div class="flex gap-3">
            <button type="submit" wire:loading.attr="disabled" class="btn-primary">
                <span wire:loading.remove wire:target="save">Save Changes</span>
                <span wire:loading wire:target="save">Saving...</span>
            </button>
            <a href="{{ route('admin.users') }}" wire:navigate class="btn-secondary">Cancel</a>
        </div>
    </form>
</div>
