<script setup lang="ts">
import CreateButton from '@/components/button/CreateButton.vue';
import { DataTable } from '@/components/data-table';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useCan } from '@/composables/useCan';
import {
    useDataTableQuery,
    useDataTableQuerySync,
} from '@/composables/useDataTableQuery';
import { EmployeeAdvanceStatus } from '@/constants/employee-advance-status';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { DataTableFilterDef, DataTableSort } from '@/types/data-table';
import type {
    EmployeeAdvanceListItem,
    EmployeeAdvancePageProps,
} from '@/types/employee-advance';
import { Head } from '@inertiajs/vue3';
import { HandCoins } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import EmployeeAdvanceFormModal from './form/EmployeeAdvanceFormModal.vue';
import RejectEmployeeAdvanceModal from './form/RejectEmployeeAdvanceModal.vue';
import { createColumns } from './table/columns';

const props = defineProps<EmployeeAdvancePageProps>();

const { can } = useCan();
const search = ref(props.filters.search ?? '');
const formModalOpen = ref(false);
const rejectModalOpen = ref(false);
const editingEmployeeAdvance = ref<EmployeeAdvanceListItem | null>(null);
const rejectingEmployeeAdvance = ref<EmployeeAdvanceListItem | null>(null);

const { query, setSearch, setSort, setFilter, resetFilters, syncFromServer } =
    useDataTableQuery({
        url: '/admin/finance/employee-advances',
        initial: { ...props.filters },
        filterKeys: ['status'],
    });

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

const columns = computed(() =>
    createColumns(props.authEmployeeId, openEditModal, openRejectModal),
);

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

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

const filterDefs = computed<DataTableFilterDef[]>(() => [
    {
        key: 'status',
        label: 'Status',
        type: 'select',
        options: [
            { value: EmployeeAdvanceStatus.PENDING, label: 'Menunggu' },
            { value: EmployeeAdvanceStatus.APPROVED, label: 'Disetujui' },
            { value: EmployeeAdvanceStatus.REJECTED, label: 'Ditolak' },
            { value: EmployeeAdvanceStatus.PAID, label: 'Lunas' },
        ],
    },
]);

const filterValues = computed(() => ({
    status: query.value.status ?? '',
}));

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

function openCreateModal() {
    editingEmployeeAdvance.value = null;
    formModalOpen.value = true;
}

function openEditModal(employeeAdvance: EmployeeAdvanceListItem) {
    editingEmployeeAdvance.value = employeeAdvance;
    formModalOpen.value = true;
}

function openRejectModal(employeeAdvance: EmployeeAdvanceListItem) {
    rejectingEmployeeAdvance.value = employeeAdvance;
    rejectModalOpen.value = true;
}

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

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

<template>
    <Head title="Kasbon" />

    <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">Kasbon</h2>
            </div>

            <CreateButton
                v-if="canSubmit"
                @click="openCreateModal"
                label="Ajukan"
            />
        </div>

        <Card v-if="can('employee_advances.verify')">
            <CardHeader
                class="flex flex-row items-center justify-between space-y-0 pb-2"
            >
                <CardTitle class="text-sm font-medium text-muted-foreground">
                    Total Kasbon
                </CardTitle>
                <HandCoins class="size-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div class="text-3xl font-bold tracking-tight">
                    {{ summary.outstanding_amount_formatted }}
                </div>
                <p class="mt-1 text-sm text-muted-foreground">
                    {{ summary.outstanding_count }} pegawai yang berhutang
                </p>
            </CardContent>
        </Card>

        <Card class="min-w-0">
            <CardContent class="min-w-0 pt-6">
                <DataTable
                    v-model:search="search"
                    :columns="columns"
                    :data="employeeAdvances.data"
                    :pagination="pagination"
                    :pagination-links="employeeAdvances.links"
                    :sort="currentSort"
                    :filter-defs="filterDefs"
                    :filter-values="filterValues"
                    @sort-change="setSort"
                    @filter-change="setFilter"
                    @filters-reset="resetFilters"
                />
            </CardContent>
        </Card>

        <EmployeeAdvanceFormModal
            v-if="canSubmit"
            v-model:open="formModalOpen"
            :employee-advance="editingEmployeeAdvance"
        />

        <RejectEmployeeAdvanceModal
            v-if="can('employee_advances.verify')"
            v-model:open="rejectModalOpen"
            :employee-advance="rejectingEmployeeAdvance"
        />
    </AdminLayout>
</template>
