<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Traits\WithTableHelpers;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Illuminate\Validation\Rules\Password;
use Livewire\WithPagination;
use App\Models\Admin;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Hash;

new #[Layout('layouts::base', ['title' => 'Admin Setting'])] class extends Component {
    use WithPagination, WithTableHelpers, WithFileUploads;

    public $name, $email, $password, $password_confirmation;
    public $editingAdmin = null;

    public int $perPage = 10;
    public int $page = 1;
    public $avatar;
    public $role;
    public $roles = ['super_admin', 'admin', 'manager']; // define roles

    /**
     * Fields that can be searched
     */
    protected function searchableFields(): array
    {
        return ['id', 'name', 'email'];
    }

    /**
     * Validation rules
     */
    protected function rules()
    {
        $rules = [
            'name' => 'required|string|max:255|unique:admins,name',
            'email' => ['required', 'email', 'max:255', Rule::unique(Admin::class, 'email')],
            'avatar' => $this->editingAdmin ? 'nullable|image|mimes:jpg,webp,avif,jpeg,png,svg|max:2048' : 'required|image|mimes:jpg,webp,avif,jpeg,png,svg|max:2048',
            'password' => ['required', 'confirmed', Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised()],
            'role' => 'required|string|in:' . implode(',', $this->roles),
        ];

        if ($this->editingAdmin) {
            $rules['name'] = ['required', 'string', 'max:255', Rule::unique('admins', 'name')->ignore($this->editingAdmin)];
            $rules['email'] = ['required', 'email', 'max:255', Rule::unique('admins', 'email')->ignore($this->editingAdmin)];

            // Password optional on edit
            $rules['password'] = ['nullable', 'confirmed', Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised()];
        }

        return $rules;
    }

    /**
     * Validate only a single property on update
     */
    public function updated($property)
    {
        $this->validateOnly($property);
    }

    /**
     * Reset pagination when perPage changes
     */
    public function updatedPerPage(): void
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }

    /**
     * Delete an admin
     */
    public function delete($id)
    {
        $adminToDelete = Admin::findOrFail($id);
        $currentAdmin = auth('admin')->user(); // use admin guard

        // Prevent deleting last admin
        if (Admin::count() <= 1) {
            $this->dispatch('showToast', 'Cannot delete the last remaining admin!', type: 'error');
            return;
        }

        // Prevent deleting self
        if ($adminToDelete->id === $currentAdmin->id) {
            $this->dispatch('showToast', 'You cannot delete your own account!', type: 'error');
            return;
        }

        // Prevent deleting super admin if logged-in admin is not super admin
        if ($adminToDelete->role === 'super_admin' && $currentAdmin->role !== 'super_admin') {
            $this->dispatch('showToast', 'You cannot delete a Super Admin!', type: 'error');
            return;
        }

        if ($adminToDelete->avatar) {
            \Storage::disk('public')->delete($adminToDelete->avatar);
        }

        $adminToDelete->delete();

        $this->dispatch('showToast', 'Admin successfully deleted', type: 'success');
    }

    /**
     * Reset the form
     */
    public function resetForm()
    {
        $this->reset(['name', 'email', 'password', 'password_confirmation', 'avatar', 'editingAdmin']);

        // Set default role
        $this->role = auth('admin')->user()->role === 'super_admin' ? 'admin' : 'manager';

        $this->resetValidation();
    }
    /**
     * Populate form for editing
     */
    public function editAdmin($id)
    {
        $admin = Admin::findOrFail($id);
        $this->editingAdmin = $admin->id;
        $this->name = $admin->name;
        $this->email = $admin->email;
        $this->role = $admin->role;
        $this->password = '';
        $this->password_confirmation = '';
    }

    /**
     * Save a new or edited admin
     */
    public function saveAdmin()
    {
        $currentUser = auth('admin')->user();

        // Determine allowed roles based on logged-in admin
        $allowedRoles = $currentUser->role === 'super_admin' ? $this->roles : array_values(array_diff($this->roles, ['super_admin']));

        // If editing, allow the current admin's role even if restricted
        if ($this->editingAdmin) {
            $editingAdminRole = Admin::find($this->editingAdmin)->role;
            if (!in_array($editingAdminRole, $allowedRoles)) {
                $allowedRoles[] = $editingAdminRole;
            }
        }

        // Base validation rules
        $rules = [
            'name' => ['required', 'string', 'max:255', $this->editingAdmin ? Rule::unique('admins', 'name')->ignore($this->editingAdmin) : Rule::unique('admins', 'name')],
            'email' => ['required', 'email', 'max:255', $this->editingAdmin ? Rule::unique('admins', 'email')->ignore($this->editingAdmin) : Rule::unique('admins', 'email')],
            'avatar' => $this->editingAdmin ? 'nullable|image|mimes:jpg,webp,avif,jpeg,png,svg|max:2048' : 'required|image|mimes:jpg,webp,avif,jpeg,png,svg|max:2048',
            'password' => $this->editingAdmin ? ['nullable', 'confirmed', Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised()] : ['required', 'confirmed', Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised()],
            'role' => ['required', 'string', Rule::in($allowedRoles)],
        ];

        // Validate
        $validated = $this->validate($rules);

        // Hash password if provided
        if (!empty($validated['password'])) {
            $validated['password'] = Hash::make($validated['password']);
        } else {
            unset($validated['password']); // keep old password
        }

        // Handle avatar upload
        if ($this->avatar) {
            $path = $this->avatar->store('admin-avatar', 'public');
            $validated['avatar'] = $path;

            if ($this->editingAdmin) {
                $admin = Admin::find($this->editingAdmin);
                if ($admin->avatar) {
                    \Storage::disk('public')->delete($admin->avatar);
                }
            }
        }

        // Save or update
        if ($this->editingAdmin) {
            Admin::findOrFail($this->editingAdmin)->update($validated);
            $message = 'Admin updated successfully!';
        } else {
            Admin::create($validated);
            $message = 'Admin created successfully!';
        }

        $this->dispatch('showToast', message: $message, type: 'success');
        $this->resetForm();
    }

    #[Computed]
    public function admins()
    {
        $query = Admin::query();

        $admin = auth('admin')->user(); // <-- use your admin guard

        if ($admin && $admin->role === 'super_admin') {
            // super admin sees all
        } else {
            // non-super admin cannot see super admins
            $query->where('role', '!=', 'super_admin');
        }

        $this->applySearch($query, $this->searchableFields());

        return $query
            ->orderBy($this->sortField ?? 'id', $this->sortDirection ?? 'desc')
            ->paginate($this->perPage)
            ->withQueryString();
    }

    public function clearError()
    {
        $this->resetErrorBag('avatar');
    }
    public function updatedAvatar()
    {
        $this->clearError();
    }
};
?>

<div class="min-h-screen bg-gray-50 dark:bg-gray-950 p-6 space-y-6">
    <!-- Dynamic Page Title -->
    <div class="mb-4">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-100">
            Manage Admin
        </h2>
    </div>
    {{-- Form --}}
    <div class="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded shadow">
        <h3 class="font-semibold text-lg mb-4">
            {{ $editingAdmin ? 'Edit Admin' : 'Add New Admin' }}
        </h3>
        <div class="space-y-4">
     <x-select 
    wire:model.defer="role" 
    label="Role" 
    :options="collect($roles)
        ->when(auth('admin')->user()->role !== 'super_admin', fn($q) => $q->reject(fn($r) => $r === 'super_admin'))
        ->mapWithKeys(fn($r) => [$r => ucfirst(str_replace('_', ' ', $r))])
        ->toArray()" 
    placeholder="Select Role" 
/>
            <flux:input wire:model.defer="name" label="Admin Name" placeholder="admin" />
            <flux:input wire:model.defer="email" label="Admin Email" placeholder="admin@example.com" />
            <flux:input wire:model.defer="password" :label="__('Password')" type="password" autocomplete="password"
                :placeholder="__('Password')" viewable />

            <flux:input wire:model.defer="password_confirmation" :label="__('Confirm Password')" type="password"
                autocomplete="confirm-password" :placeholder="__('Confirm Password')" viewable />
            <x-ui.custom-file-upload model="avatar" label="Upload Admin Avatar" accepted-file-types="image/*" />
            <flux:button wire:click="saveAdmin" variant="primary" color="indigo" class="w-full text-center py-3">
                {{ $editingAdmin ? 'Update Admin' : 'Add Admin' }}
            </flux:button>
            @if ($editingAdmin)
                <button wire:click="resetForm"
                    class="mt-3 px-4 py-2 bg-gray-400 text-white rounded hover:bg-gray-500 ml-2">
                    Cancel
                </button>
            @endif
        </div>

    </div>

    {{-- Admin List --}}
    <div class="space-y-6">

        {{-- Search Bar --}}
        <div class="w-full md:w-1/2">
            <div class="relative">
                <x-flux::icon.magnifying-glass
                    class="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
                <input type="text" wire:model.live="search" placeholder="Search by name or email"
                    class="w-full pl-12 pr-4 py-3 text-sm rounded-xl bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition" />
            </div>
        </div>

        {{-- Admin Cards --}}
        @foreach ($this->admins as $admin)
            <div
                class="flex flex-col md:flex-row md:justify-between md:items-center p-6 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl shadow-sm hover:shadow-md transition duration-300">

                {{-- Left: Admin Info --}}
                <div class="flex flex-col md:flex-row md:items-center md:gap-6">
                    <div class="shrink-0">
                        @if ($admin->avatar)
                            <img src="{{ Storage::disk('public')->url($admin->avatar) }}"
                                class="w-12 h-12 rounded-full object-cover shadow" />
                        @else
                            <div
                                class="w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-gray-500 dark:text-gray-400 font-semibold text-lg">
                                {{ strtoupper(substr($admin->name, 0, 1)) }}
                            </div>
                        @endif
                    </div>

                    <div class="mt-3 md:mt-0 flex flex-col gap-1">
                        <span class="font-semibold text-gray-900 dark:text-gray-100 text-lg">
                            {{ $admin->name }}
                        </span>
                        <span
                            class="text-sm px-2 py-1 rounded-full w-fit
    {{ $admin->role === 'super_admin' ? 'bg-red-500 text-white' : ($admin->role === 'manager' ? 'bg-green-500 text-white' : 'bg-blue-500 text-white') }}">
                            {{ ucfirst($admin->role) }}
                        </span>
                        <span class="text-gray-500 dark:text-gray-400 text-sm">
                            {{ $admin->email }}
                        </span>
                    </div>
                </div>

                {{-- Right: Actions --}}
                <div class="flex items-center gap-3 mt-4 md:mt-0">

                    {{-- Edit Button --}}
                    <x-flux::button wire:click="editAdmin({{ $admin->id }})" variant="primary" color="green" type="button">
                        Edit
                    </x-flux::button>

                    {{-- Delete Button --}}
                    <x-flux::button x-data variant="danger" type="button"
                        @click.prevent="if (confirm('Are you sure you want to delete this admin?')) { $wire.delete({{ $admin->id }}) }">
                        Delete
                    </x-flux::button>

                </div>
            </div>
        @endforeach

    </div>

</div>
