<script setup lang="ts">
import { Head, Link } from '@inertiajs/vue3';
import { Plus } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { createColumns, type RoleListItem } from './table/columns';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useCan } from '@/composables/useCan';
import {
    useDataTableQuery,
    useDataTableQuerySync,
} from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { DataTableSort } from '@/types/data-table';

interface PaginatedRoles {
    current_page: number;
    per_page: number;
    last_page: number;
    total: number;
    data: RoleListItem[];
    links: any[];
}

const props = defineProps<{
    roles: PaginatedRoles;
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
    };
}>();

const { can } = useCan();
const search = ref(props.filters.search ?? '');

const { query, setSearch, setSort, resetFilters, syncFromServer } = useDataTableQuery({
    url: '/admin/system/roles',
    initial: { ...props.filters },
});

useDataTableQuerySync(() => props.filters, syncFromServer);

const columns = computed(() => createColumns());

const currentSort = computed<DataTableSort | null>(() => {
    if (!query.value.sort || !query.value.direction) {
        return null;
    }

    return {
        column: query.value.sort,
        direction: query.value.direction,
    };
});

const pagination = computed(() => ({
    currentPage: props.roles.current_page,
    perPage: props.roles.per_page,
    lastPage: props.roles.last_page,
    total: props.roles.total,
}));

watch(search, (value) => {
    setSearch(value);
});

watch(
    () => props.filters.search,
    (value) => {
        search.value = value ?? '';
    },
);
</script>

<template>
    <Head title="Role & Permission" />

    <AdminLayout>
        <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div class="space-y-1">
                <h2 class="text-2xl font-bold tracking-tight">
                    Role & Permission
                </h2>
            </div>

            <Button v-if="can('roles.create')" class="shrink-0 self-start sm:self-center" as-child>
                <Link href="/admin/system/roles/create">
                    <Plus class="size-4" />
                    Tambah
                </Link>
            </Button>
        </div>

        <Card class="min-w-0">
            <CardContent class="min-w-0">
                <DataTable v-model:search="search" :columns="columns" :data="roles.data" :pagination="pagination"
                    :pagination-links="roles.links" :sort="currentSort" @sort-change="setSort"
                    @filters-reset="resetFilters" />
            </CardContent>
        </Card>
    </AdminLayout>
</template>
