<template>
    <div class="space-y-6">
        <Head title="Account" />

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <h2 class="text-lg font-semibold">Account</h2>
                    <p class="text-sm text-slate-500">
                        Manage users, access, and status assignments.
                    </p>
                </div>
                <div class="flex items-center gap-2">
                    <button
                        class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700"
                        type="button"
                    >
                        Users
                    </button>
                    <button
                        class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                        type="button"
                        @click="openCreate"
                    >
                        Register
                    </button>
                </div>
            </div>

            <div class="mt-6 grid gap-3 lg:grid-cols-4">
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Search
                    </label>
                    <input
                        v-model="search"
                        type="text"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        placeholder="Search name, email, or role..."
                    />
                </div>
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Role
                    </label>
                    <select
                        v-model="roleFilter"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="all">All roles</option>
                        <option
                            v-for="role in roles"
                            :key="role.id"
                            :value="role.id"
                        >
                            {{ role.name }}
                        </option>
                    </select>
                </div>
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Status
                    </label>
                    <select
                        v-model="statusFilter"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="all">All status</option>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
                <div class="flex items-end gap-2">
                    <button
                        class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600"
                        type="button"
                        @click="resetFilters"
                    >
                        Clear
                    </button>
                </div>
            </div>

            <div class="mt-6 grid gap-4 sm:grid-cols-6">
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Total</p>
                    <p class="mt-2 text-lg font-semibold">{{ totalCount }}</p>
                </div>
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Active</p>
                    <p class="mt-2 text-lg font-semibold text-emerald-700">
                        {{ activeCount }}
                    </p>
                </div>
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Inactive</p>
                    <p class="mt-2 text-lg font-semibold text-slate-600">
                        {{ inactiveCount }}
                    </p>
                </div>
            </div>

            <div class="mt-6 overflow-hidden rounded-lg border border-slate-100">
                <table class="w-full text-left text-sm">
                    <thead class="bg-slate-50 text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Name</th>
                            <th class="px-4 py-3">Role</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Joined</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="user in pagedUsers"
                            :key="user.id"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3">
                                <div class="flex items-center gap-3">
                                    <span
                                        class="flex h-9 w-9 items-center justify-center rounded-full bg-slate-100 text-xs font-semibold text-slate-600"
                                    >
                                        {{ initials(user.name) }}
                                    </span>
                                    <div>
                                        <p class="font-semibold text-slate-700">
                                            {{ user.name }}
                                        </p>
                                        <p class="text-xs text-slate-400">
                                            {{ user.email }}
                                        </p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    class="rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-700"
                                >
                                    {{ user.role || 'Unassigned' }}
                                </span>
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    class="rounded-full px-2 py-1 text-xs font-semibold"
                                    :class="statusClass(user.status)"
                                >
                                    {{ statusLabel(user.status) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ user.created_at || '—' }}
                            </td>
                            <td class="px-4 py-3 text-right">
                                <button
                                    class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                    type="button"
                                    @click="openEdit(user)"
                                >
                                    Edit
                                </button>
                            </td>
                        </tr>
                        <tr v-if="pagedUsers.length === 0">
                            <td
                                class="px-4 py-6 text-center text-sm text-slate-500"
                                colspan="5"
                            >
                                No users found.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div
                class="mt-6 flex flex-wrap items-center justify-between gap-3 text-sm text-slate-500"
            >
                <div>
                    Showing {{ pageStart }} to {{ pageEnd }} of
                    {{ totalCount }} users
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs uppercase text-slate-400">Rows</label>
                    <select
                        v-model.number="perPage"
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs"
                    >
                        <option :value="5">5</option>
                        <option :value="10">10</option>
                        <option :value="20">20</option>
                    </select>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs"
                        type="button"
                        :disabled="page === 1"
                        @click="page--"
                    >
                        Prev
                    </button>
                    <span class="text-xs">
                        {{ page }} / {{ totalPages }}
                    </span>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs"
                        type="button"
                        :disabled="page === totalPages"
                        @click="page++"
                    >
                        Next
                    </button>
                </div>
            </div>
        </div>

        <div
            v-if="showModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-lg rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">
                            {{ isEditing ? 'Edit User' : 'Register User' }}
                        </h3>
                        <p class="text-sm text-slate-500">
                            {{ isEditing ? 'Update user details.' : 'Add a new user.' }}
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeModal"
                    >
                        Close
                    </button>
                </div>

                <form class="mt-6 space-y-4" @submit.prevent="submit">
                    <div>
                        <label class="text-sm font-medium">Name</label>
                        <input
                            v-model="form.name"
                            type="text"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                            placeholder="Full name"
                        />
                        <p v-if="form.errors.name" class="mt-1 text-xs text-red-600">
                            {{ form.errors.name }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Email</label>
                        <input
                            v-model="form.email"
                            type="email"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                            placeholder="email@example.com"
                        />
                        <p v-if="form.errors.email" class="mt-1 text-xs text-red-600">
                            {{ form.errors.email }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Role</label>
                        <select
                            v-model="form.role_id"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        >
                            <option value="">Unassigned</option>
                            <option
                                v-for="role in roles"
                                :key="role.id"
                                :value="role.id"
                            >
                                {{ role.name }}
                            </option>
                        </select>
                        <p v-if="form.errors.role_id" class="mt-1 text-xs text-red-600">
                            {{ form.errors.role_id }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">
                            Password
                            <span v-if="isEditing" class="text-xs text-slate-400">
                                (leave blank to keep)
                            </span>
                        </label>
                        <input
                            v-model="form.password"
                            type="password"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                            placeholder="••••••••"
                        />
                        <p
                            v-if="form.errors.password"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ form.errors.password }}
                        </p>
                    </div>
                    <label class="flex items-center gap-2 text-sm text-slate-600">
                        <input
                            v-model="form.status"
                            type="checkbox"
                            class="rounded border-slate-300"
                        />
                        Active
                    </label>
                    <div class="flex justify-end gap-2">
                        <button
                            class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                            type="button"
                            @click="closeModal"
                        >
                            Cancel
                        </button>
                        <button
                            class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                            type="submit"
                            :disabled="form.processing"
                        >
                            {{ isEditing ? 'Save Changes' : 'Create User' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div
            v-if="showNotice"
            class="fixed inset-0 z-60 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-sm rounded-2xl bg-white p-6 text-center">
                <h3 class="text-lg font-semibold">Success</h3>
                <p class="mt-2 text-sm text-slate-500">{{ noticeMessage }}</p>
                <button
                    class="mt-6 rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                    type="button"
                    @click="closeNotice"
                >
                    Ok
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { Head, useForm } from '@inertiajs/vue3';
import AuthenticatedLayout from '../../Layouts/AuthenticatedLayout.vue';

const props = defineProps({
    users: {
        type: Array,
        default: () => [],
    },
    roles: {
        type: Array,
        default: () => [],
    },
});

defineOptions({
    layout: (h, page) => h(AuthenticatedLayout, { title: 'Account' }, () => page),
});

const search = ref('');
const statusFilter = ref('all');
const roleFilter = ref('all');
const perPage = ref(10);
const page = ref(1);

const initialForm = {
    id: null,
    name: '',
    email: '',
    role_id: '',
    password: '',
    status: true,
};

const form = useForm({ ...initialForm });
const showModal = ref(false);
const isEditing = ref(false);
const showNotice = ref(false);
const noticeMessage = ref('');

const filteredUsers = computed(() => {
    const term = search.value.trim().toLowerCase();
    return props.users.filter((user) => {
        const matchesSearch = term
            ? [user.name, user.email, user.role]
                  .filter(Boolean)
                  .some((value) => value.toLowerCase().includes(term))
            : true;
        const matchesStatus =
            statusFilter.value === 'all'
                ? true
                : user.status === statusFilter.value;
        const matchesRole =
            roleFilter.value === 'all'
                ? true
                : Number(user.role_id) === Number(roleFilter.value);
        return matchesSearch && matchesStatus && matchesRole;
    });
});

const totalCount = computed(() => filteredUsers.value.length);
const activeCount = computed(
    () => filteredUsers.value.filter((user) => user.status === 'active').length
);
const inactiveCount = computed(
    () => filteredUsers.value.filter((user) => user.status === 'inactive').length
);

const totalPages = computed(() =>
    Math.max(1, Math.ceil(totalCount.value / perPage.value))
);
const pageStart = computed(() =>
    totalCount.value === 0 ? 0 : (page.value - 1) * perPage.value + 1
);
const pageEnd = computed(() =>
    Math.min(page.value * perPage.value, totalCount.value)
);
const pagedUsers = computed(() =>
    filteredUsers.value.slice(
        (page.value - 1) * perPage.value,
        page.value * perPage.value
    )
);

watch([search, statusFilter, roleFilter, perPage], () => {
    page.value = 1;
});

watch(filteredUsers, () => {
    if (page.value > totalPages.value) {
        page.value = totalPages.value;
    }
});

const resetFilters = () => {
    search.value = '';
    statusFilter.value = 'all';
    roleFilter.value = 'all';
};

const openCreate = () => {
    isEditing.value = false;
    form.reset();
    form.clearErrors();
    form.status = true;
    form.role_id = '';
    showModal.value = true;
};

const openEdit = (user) => {
    isEditing.value = true;
    form.clearErrors();
    form.id = user.id;
    form.name = user.name;
    form.email = user.email;
    form.role_id = user.role_id ?? '';
    form.password = '';
    form.status = user.status === 'active';
    showModal.value = true;
};

const closeModal = () => {
    showModal.value = false;
};

const openNotice = (message) => {
    noticeMessage.value = message;
    showNotice.value = true;
};

const closeNotice = () => {
    showNotice.value = false;
};

const submit = () => {
    if (isEditing.value) {
        form.put(`/account/users/${form.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                showModal.value = false;
                openNotice('User updated successfully.');
            },
        });
    } else {
        form.post('/account/users', {
            preserveScroll: true,
            onSuccess: () => {
                showModal.value = false;
                openNotice('User created successfully.');
            },
        });
    }
};

const initials = (name) =>
    name
        .split(' ')
        .slice(0, 2)
        .map((part) => part[0])
        .join('')
        .toUpperCase();

const statusLabel = (status) => (status === 'active' ? 'Active' : 'Inactive');

const statusClass = (status) => {
    const map = {
        active: 'bg-emerald-50 text-emerald-700',
        inactive: 'bg-slate-100 text-slate-600',
    };
    return map[status] ?? 'bg-slate-100 text-slate-600';
};
</script>
