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

        <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">Access Roles</h2>
                    <p class="text-sm text-slate-500">
                        Manage role names and assigned user counts.
                    </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"
                    >
                        Roles
                    </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 role name..."
                    />
                </div>
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Assignment
                    </label>
                    <select
                        v-model="assignmentFilter"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="all">All roles</option>
                        <option value="assigned">Assigned</option>
                        <option value="unassigned">Unassigned</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">Assigned</p>
                    <p class="mt-2 text-lg font-semibold text-emerald-700">
                        {{ assignedCount }}
                    </p>
                </div>
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Unassigned</p>
                    <p class="mt-2 text-lg font-semibold text-slate-600">
                        {{ unassignedCount }}
                    </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">Role</th>
                            <th class="px-4 py-3">Users</th>
                            <th class="px-4 py-3">Created</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="role in pagedRoles"
                            :key="role.id"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3">
                                <p class="font-semibold text-slate-700">
                                    {{ role.name }}
                                </p>
                            </td>
                            <td class="px-4 py-3 text-slate-600">
                                {{ role.users_count }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ role.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(role)"
                                >
                                    Edit
                                </button>
                            </td>
                        </tr>
                        <tr v-if="pagedRoles.length === 0">
                            <td
                                class="px-4 py-6 text-center text-sm text-slate-500"
                                colspan="4"
                            >
                                No roles 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 }} roles
                </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 Role' : 'Register Role' }}
                        </h3>
                        <p class="text-sm text-slate-500">
                            {{ isEditing ? 'Update role details.' : 'Add a new role.' }}
                        </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">Role 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="e.g. Manager"
                        />
                        <p v-if="form.errors.name" class="mt-1 text-xs text-red-600">
                            {{ form.errors.name }}
                        </p>
                    </div>
                    <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 Role' }}
                        </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({
    roles: {
        type: Array,
        default: () => [],
    },
});

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

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

const form = useForm({
    id: null,
    name: '',
});
const showModal = ref(false);
const isEditing = ref(false);
const showNotice = ref(false);
const noticeMessage = ref('');

const filteredRoles = computed(() => {
    const term = search.value.trim().toLowerCase();
    return props.roles.filter((role) => {
        const matchesSearch = term
            ? role.name.toLowerCase().includes(term)
            : true;
        const matchesAssignment =
            assignmentFilter.value === 'all'
                ? true
                : assignmentFilter.value === 'assigned'
                  ? role.users_count > 0
                  : role.users_count === 0;
        return matchesSearch && matchesAssignment;
    });
});

const totalCount = computed(() => filteredRoles.value.length);
const assignedCount = computed(
    () => filteredRoles.value.filter((role) => role.users_count > 0).length
);
const unassignedCount = computed(
    () => filteredRoles.value.filter((role) => role.users_count === 0).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 pagedRoles = computed(() =>
    filteredRoles.value.slice(
        (page.value - 1) * perPage.value,
        page.value * perPage.value
    )
);

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

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

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

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

const openEdit = (role) => {
    isEditing.value = true;
    form.clearErrors();
    form.id = role.id;
    form.name = role.name;
    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(`/access-roles/${form.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                showModal.value = false;
                openNotice('Role updated successfully.');
            },
        });
    } else {
        form.post('/access-roles', {
            preserveScroll: true,
            onSuccess: () => {
                showModal.value = false;
                openNotice('Role created successfully.');
            },
        });
    }
};
</script>
