<script setup lang="ts">
import { ref, watch } from 'vue';
import { Head, useForm, router, usePage } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, UserPlus, Edit2, Trash2, Shield, Mail, User, Key, Check } from 'lucide-vue-next';

interface Role {
    id: number;
    name: string;
}

interface UserData {
    id: number;
    name: string;
    email: string;
    roles: { id: number; name: string }[];
    created_at: string;
}

interface PaginatedUsers {
    data: UserData[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
}

const props = defineProps<{
    users: PaginatedUsers;
    roles: Role[];
    filters: {
        search?: string;
        role?: string;
    };
}>();

const search = ref(props.filters.search || '');
const roleFilter = ref(props.filters.role || '');

// Debounce search and role filter changes
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const performFilter = () => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
        router.get(
            route('users.index'),
            { search: search.value, role: roleFilter.value },
            { preserveState: true, replace: true }
        );
    }, 400);
};

watch(search, performFilter);
watch(roleFilter, performFilter);

// Modal state
const isFormModalOpen = ref(false);
const isDeleteModalOpen = ref(false);
const editingUser = ref<UserData | null>(null);
const userToDelete = ref<UserData | null>(null);

// Form configuration
const form = useForm({
    name: '',
    email: '',
    password: '',
    roles: [] as string[],
});

const openCreateModal = () => {
    editingUser.value = null;
    form.clearErrors();
    form.reset();
    isFormModalOpen.value = true;
};

const page = usePage<any>();

const openEditModal = (user: UserData) => {
    editingUser.value = user;
    form.clearErrors();
    form.name = user.name;
    form.email = user.email;
    form.password = '';
    form.roles = user.roles.map(r => r.name);
    isFormModalOpen.value = true;
};

const submitForm = () => {
    if (editingUser.value) {
        form.put(route('users.update', editingUser.value.id), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    } else {
        form.post(route('users.store'), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    }
};

const openDeleteModal = (user: UserData) => {
    userToDelete.value = user;
    isDeleteModalOpen.value = true;
};

const deleteUser = () => {
    if (!userToDelete.value) return;
    router.delete(route('users.destroy', userToDelete.value.id), {
        onSuccess: () => {
            isDeleteModalOpen.value = false;
            userToDelete.value = null;
        },
    });
};

const toggleFormRole = (roleName: string) => {
    const idx = form.roles.indexOf(roleName);
    if (idx > -1) {
        form.roles.splice(idx, 1);
    } else {
        form.roles.push(roleName);
    }
};

// Helpers for avatar generation
const getInitials = (name: string | null | undefined) => {
    if (!name) return 'U';
    const parts = name.trim().split(/\s+/).filter(Boolean);
    if (parts.length === 0) return 'U';
    return parts.map(n => n[0]).slice(0, 2).join('').toUpperCase();
};
</script>

<template>
    <Head title="User Management" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header Section -->
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-50">User Management</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Create, modify, and assign security roles to system users.
                    </p>
                </div>
                <div>
                    <button
                        @click="openCreateModal"
                        class="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                    >
                        <UserPlus class="h-4 w-4" />
                        Add User
                    </button>
                </div>
            </div>

            <!-- Toast Messages -->
            <div v-if="page.props.flash?.success" class="bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-900/50 text-emerald-800 dark:text-emerald-400 rounded-xl p-4 text-sm flex items-center gap-3">
                <Check class="h-5 w-5 text-emerald-600 dark:text-emerald-400 shrink-0" />
                <span>{{ page.props.flash?.success }}</span>
            </div>
            <div v-if="page.props.flash?.error" class="bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900/50 text-rose-800 dark:text-rose-400 rounded-xl p-4 text-sm flex items-center gap-3">
                <span class="font-bold text-rose-600 dark:text-rose-400">Error:</span>
                <span>{{ page.props.flash?.error }}</span>
            </div>

            <!-- Filters Section -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-4 shadow-sm flex flex-col md:flex-row gap-4 items-center justify-between">
                <div class="flex flex-col md:flex-row w-full md:items-center gap-4">
                    <div class="relative w-full md:max-w-xs">
                        <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400 dark:text-slate-500" />
                        <input
                            v-model="search"
                            type="text"
                            placeholder="Search by name or email..."
                            class="w-full pl-9 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                        />
                    </div>
                    <div class="w-full md:w-48">
                        <select
                            v-model="roleFilter"
                            class="w-full px-3 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                        >
                            <option value="">All Roles</option>
                            <option v-for="role in roles" :key="role.id" :value="role.name">
                                {{ role.name }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="text-sm text-slate-500 dark:text-slate-400 whitespace-nowrap">
                    Total Users: <span class="font-semibold text-slate-900 dark:text-slate-50">{{ users.total }}</span>
                </div>
            </div>

            <!-- Users Data Table -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left">
                        <thead>
                            <tr class="border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                                <th class="px-6 py-4">User</th>
                                <th class="px-6 py-4">Assigned Roles</th>
                                <th class="px-6 py-4">Created Date</th>
                                <th class="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800 text-sm">
                            <tr v-if="users.data.length === 0">
                                <td colspan="4" class="px-6 py-12 text-center text-slate-500 dark:text-slate-400">
                                    No users match your filters.
                                </td>
                            </tr>
                            <tr 
                                v-for="user in users.data" 
                                :key="user.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/50 transition-colors"
                            >
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-3">
                                        <div class="h-9 w-9 rounded-full bg-gradient-to-br from-red-500 to-rose-600 text-white flex items-center justify-center font-bold text-xs shadow-sm">
                                            {{ getInitials(user.name) }}
                                        </div>
                                        <div>
                                            <div class="font-medium text-slate-900 dark:text-slate-100 flex items-center gap-1.5">
                                                {{ user.name }}
                                                <span v-if="user.id === page.props.auth.user.id" class="text-[10px] font-semibold bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-400 px-1.5 py-0.5 rounded-full border border-red-100 dark:border-red-900/50">You</span>
                                            </div>
                                            <div class="text-xs text-slate-500 dark:text-slate-400">{{ user.email }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex flex-wrap gap-1">
                                        <span 
                                            v-for="role in user.roles" 
                                            :key="role.id"
                                            :class="[
                                                'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border',
                                                role.name === 'Super Admin'
                                                    ? 'bg-slate-900 text-slate-50 border-slate-800 dark:bg-slate-50 dark:text-slate-900 dark:border-slate-200'
                                                    : 'bg-red-50 text-red-700 border-red-150 dark:bg-red-950/30 dark:text-red-400 dark:border-red-900/50'
                                            ]"
                                        >
                                            <Shield class="h-3 w-3" />
                                            {{ role.name }}
                                        </span>
                                        <span v-if="user.roles.length === 0" class="text-xs text-slate-400 italic">No Roles</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-slate-500 dark:text-slate-400 whitespace-nowrap">
                                    {{ user.created_at }}
                                </td>
                                <td class="px-6 py-4 text-right whitespace-nowrap">
                                    <div class="flex items-center justify-end gap-2">
                                        <button
                                            @click="openEditModal(user)"
                                            class="p-1.5 rounded-lg text-slate-500 hover:text-slate-900 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors"
                                            title="Edit User"
                                        >
                                            <Edit2 class="h-4 w-4" />
                                        </button>
                                        <button
                                            @click="openDeleteModal(user)"
                                            :disabled="user.id === page.props.auth.user.id"
                                            class="p-1.5 rounded-lg text-slate-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-slate-400 cursor-pointer disabled:cursor-not-allowed"
                                            title="Delete User"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination Footer -->
                <div 
                    v-if="users.last_page > 1"
                    class="border-t border-slate-200 dark:border-slate-800 px-6 py-4 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50"
                >
                    <div class="flex-1 flex justify-between sm:hidden">
                        <button
                            :disabled="!users.prev_page_url"
                            @click="users.prev_page_url && router.visit(users.prev_page_url)"
                            class="relative inline-flex items-center px-4 py-2 border border-slate-300 dark:border-slate-800 text-sm font-medium rounded-md text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 hover:bg-slate-50 dark:hover:bg-slate-900 disabled:opacity-50 transition-colors"
                        >
                            Previous
                        </button>
                        <button
                            :disabled="!users.next_page_url"
                            @click="users.next_page_url && router.visit(users.next_page_url)"
                            class="ml-3 relative inline-flex items-center px-4 py-2 border border-slate-300 dark:border-slate-800 text-sm font-medium rounded-md text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 hover:bg-slate-50 dark:hover:bg-slate-900 disabled:opacity-50 transition-colors"
                        >
                            Next
                        </button>
                    </div>
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div>
                            <p class="text-sm text-slate-700 dark:text-slate-400">
                                Showing page <span class="font-medium text-slate-900 dark:text-slate-50">{{ users.current_page }}</span> of <span class="font-medium text-slate-900 dark:text-slate-50">{{ users.last_page }}</span>
                            </p>
                        </div>
                        <div>
                            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                <button
                                    v-for="(link, idx) in users.links"
                                    :key="idx"
                                    :disabled="!link.url"
                                    @click="link.url && router.visit(link.url)"
                                    v-html="link.label"
                                    :class="[
                                        link.active 
                                            ? 'z-10 bg-red-500 border-red-500 text-white focus:ring-red-500' 
                                            : 'bg-white dark:bg-slate-950 border-slate-300 dark:border-slate-800 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900',
                                        'relative inline-flex items-center px-3 py-2 border text-xs font-medium disabled:opacity-50 transition-colors cursor-pointer',
                                        idx === 0 ? 'rounded-l-md' : '',
                                        idx === users.links.length - 1 ? 'rounded-r-md' : ''
                                    ]"
                                />
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Create/Edit Form Modal -->
        <div 
            v-if="isFormModalOpen" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4"
        >
            <!-- Backdrop -->
            <div 
                @click="isFormModalOpen = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm transition-opacity"
            />

            <!-- Modal Content -->
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-lg overflow-hidden flex flex-col max-h-[90vh] animate-in zoom-in-95 duration-200">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
                    <h3 class="text-base font-semibold text-slate-900 dark:text-slate-50">
                        {{ editingUser ? 'Edit User details' : 'Create new User' }}
                    </h3>
                    <button 
                        @click="isFormModalOpen = false"
                        class="rounded-lg p-1 text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-900 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
                    >
                        &times;
                    </button>
                </div>

                <form @submit.prevent="submitForm" class="flex flex-col overflow-hidden">
                    <div class="p-6 overflow-y-auto space-y-5">
                        <!-- Name Input -->
                        <div class="space-y-1.5">
                            <label for="form-name" class="block text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Full Name</label>
                            <div class="relative">
                                <User class="absolute left-3 top-2.5 h-4.5 w-4.5 text-slate-400" />
                                <input
                                    id="form-name"
                                    v-model="form.name"
                                    type="text"
                                    required
                                    placeholder="Jane Doe"
                                    class="w-full pl-10 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                                />
                            </div>
                            <span v-if="form.errors.name" class="text-xs text-red-600 dark:text-red-400 font-medium">{{ form.errors.name }}</span>
                        </div>

                        <!-- Email Input -->
                        <div class="space-y-1.5">
                            <label for="form-email" class="block text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Email Address</label>
                            <div class="relative">
                                <Mail class="absolute left-3 top-2.5 h-4.5 w-4.5 text-slate-400" />
                                <input
                                    id="form-email"
                                    v-model="form.email"
                                    type="email"
                                    required
                                    placeholder="jane.doe@example.com"
                                    class="w-full pl-10 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                                />
                            </div>
                            <span v-if="form.errors.email" class="text-xs text-red-600 dark:text-red-400 font-medium">{{ form.errors.email }}</span>
                        </div>

                        <!-- Password Input -->
                        <div class="space-y-1.5">
                            <label for="form-password" class="block text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">
                                Password <span v-if="editingUser" class="text-[10px] text-slate-400 italic normal-case font-normal">(Leave blank to keep current)</span>
                            </label>
                            <div class="relative">
                                <Key class="absolute left-3 top-2.5 h-4.5 w-4.5 text-slate-400" />
                                <input
                                    id="form-password"
                                    v-model="form.password"
                                    type="password"
                                    :required="!editingUser"
                                    placeholder="••••••••"
                                    class="w-full pl-10 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                                />
                            </div>
                            <span v-if="form.errors.password" class="text-xs text-red-600 dark:text-red-400 font-medium">{{ form.errors.password }}</span>
                        </div>

                        <!-- Role Checklist -->
                        <div class="space-y-2">
                            <span class="block text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Assign Security Roles</span>
                            <div class="grid grid-cols-2 gap-3 border border-slate-200 dark:border-slate-800 rounded-lg p-3.5 bg-slate-50/50 dark:bg-slate-900/30">
                                <div 
                                    v-for="role in roles" 
                                    :key="role.id"
                                    class="flex items-center space-x-2.5 cursor-pointer select-none"
                                    @click="toggleFormRole(role.name)"
                                >
                                    <div 
                                        :class="[
                                            'h-4.5 w-4.5 rounded border flex items-center justify-center transition-all',
                                            form.roles.includes(role.name) 
                                                ? 'bg-red-500 border-red-500 text-white' 
                                                : 'border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900'
                                        ]"
                                    >
                                        <Check v-if="form.roles.includes(role.name)" class="h-3 w-3 stroke-[3]" />
                                    </div>
                                    <span class="text-sm font-medium text-slate-700 dark:text-slate-350 capitalize">{{ role.name }}</span>
                                </div>
                            </div>
                            <span v-if="form.errors.roles" class="text-xs text-red-600 dark:text-red-400 font-medium">{{ form.errors.roles }}</span>
                        </div>
                    </div>

                    <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 flex justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/50">
                        <button
                            type="button"
                            @click="isFormModalOpen = false"
                            class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors focus:outline-none"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="form.processing"
                            class="px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50"
                        >
                            <span v-if="form.processing">Saving...</span>
                            <span v-else>Save Changes</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div 
            v-if="isDeleteModalOpen" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4"
        >
            <!-- Backdrop -->
            <div 
                @click="isDeleteModalOpen = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm"
            />

            <!-- Modal Content -->
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col animate-in zoom-in-95 duration-200">
                <div class="p-6 text-center space-y-4">
                    <div class="mx-auto h-12 w-12 rounded-full bg-red-50 dark:bg-red-950/30 flex items-center justify-center border border-red-100 dark:border-red-900/50 text-red-600 dark:text-red-400">
                        <Trash2 class="h-6 w-6" />
                    </div>
                    <div class="space-y-1">
                        <h3 class="text-base font-bold text-slate-900 dark:text-slate-50">Delete User Account</h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400 leading-normal">
                            Are you sure you want to delete <span class="font-semibold text-slate-950 dark:text-slate-50">{{ userToDelete?.name }}</span>? This action is permanent and cannot be undone.
                        </p>
                    </div>
                </div>

                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 flex justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/50">
                    <button
                        type="button"
                        @click="isDeleteModalOpen = false"
                        class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        @click="deleteUser"
                        class="px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow-sm transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                    >
                        Yes, Delete User
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
