<script setup lang="ts">
import { Head } from '@inertiajs/vue3';
import { Banknote } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { DataTable } from '@/components/data-table';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import Empty from '@/components/ui/empty/Empty.vue';
import EmptyDescription from '@/components/ui/empty/EmptyDescription.vue';
import EmptyHeader from '@/components/ui/empty/EmptyHeader.vue';
import EmptyTitle from '@/components/ui/empty/EmptyTitle.vue';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCan } from '@/composables/useCan';
import {
    useDataTableQuery,
    useDataTableQuerySync,
} from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { DataTableSort } from '@/types/data-table';
import type { PayrollListItem, PayrollPageProps } from '@/types/payroll';
import PayrollAdjustmentModal from './form/PayrollAdjustmentModal.vue';
import { createColumns } from './table/columns';

import { index } from '@/routes/admin/finance/payroll';

const props = defineProps<PayrollPageProps>();

const { can } = useCan();
const search = ref(props.filters.search ?? '');
const selectedPeriodId = ref(
    props.filters.period_id ? String(props.filters.period_id) : '',
);
const adjustmentModalOpen = ref(false);
const adjustingPayroll = ref<PayrollListItem | null>(null);
const currentAdjustingPayroll = computed(() => {
    const current = adjustingPayroll.value;

    if (!current || !props.payrolls?.data) {
        return current;
    }

    return props.payrolls.data.find((p) => p.id === current.id) ?? current;
});

const { query, setSearch, setSort, setFilter, resetFilters, syncFromServer } =
    useDataTableQuery({
        url: index.url(),
        initial: {
            ...props.filters,
            period_id: props.filters.period_id
                ? String(props.filters.period_id)
                : '',
        },
        filterKeys: ['period_id'],
    });

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

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

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(() => {
    if (!props.payrolls) {
        return null;
    }

    return {
        currentPage: props.payrolls.current_page,
        perPage: props.payrolls.per_page,
        lastPage: props.payrolls.last_page,
        total: props.payrolls.total,
    };
});

function openAdjustModal(payroll: PayrollListItem) {
    adjustingPayroll.value = payroll;
    adjustmentModalOpen.value = true;
}

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

watch(selectedPeriodId, (value) => {
    setFilter('period_id', value);
});

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

watch(
    () => props.filters.period_id,
    (value) => {
        selectedPeriodId.value = value ? String(value) : '';
    },
);
</script>

<template>

    <Head title="Gaji" />

    <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">Gaji</h2>
                <p v-if="currentPeriod" class="text-sm text-muted-foreground">
                    Periode {{ currentPeriod.period_label }}
                    <Badge class="ml-2" :variant="currentPeriod.status === 'open'
                        ? 'default'
                        : 'secondary'
                        ">
                        {{ currentPeriod.status_label }}
                    </Badge>
                </p>
            </div>

            <div class="flex shrink-0 flex-col gap-2 sm:flex-row sm:items-center">
                <Select v-if="periods.length > 0" v-model="selectedPeriodId">
                    <SelectTrigger class="w-full sm:w-[200px]">
                        <SelectValue placeholder="Pilih periode" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem v-for="period in periods" :key="period.id" :value="String(period.id)">
                            {{ period.period_label }}
                        </SelectItem>
                    </SelectContent>
                </Select>
            </div>
        </div>

        <Card v-if="summary">
            <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle class="text-sm font-medium text-muted-foreground">
                    Total Gaji Periode
                </CardTitle>
                <Banknote class="size-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div class="text-3xl font-bold tracking-tight">
                    {{ summary.total_amount_formatted }}
                </div>
                <p class="mt-1 text-sm text-muted-foreground">
                    {{ summary.total_count }} slip gaji
                </p>
            </CardContent>
        </Card>

        <Card v-if="payrolls && pagination" class="min-w-0">
            <CardContent class="min-w-0 pt-6">
                <DataTable v-model:search="search" :columns="columns" :data="payrolls.data" :pagination="pagination"
                    :pagination-links="payrolls.links" :sort="currentSort" @sort-change="setSort"
                    @filters-reset="resetFilters" />
            </CardContent>
        </Card>

        <div v-else class="rounded-md border px-6 py-10">
            <Empty>
                <EmptyHeader>
                    <EmptyTitle>Data tidak ditemukan</EmptyTitle>
                    <EmptyDescription>
                        Silakan lakukan pencarian untuk menemukan data yang Anda
                        cari.
                    </EmptyDescription>
                </EmptyHeader>
            </Empty>
        </div>

        <PayrollAdjustmentModal v-if="can('payroll.adjust')" v-model:open="adjustmentModalOpen"
            :payroll="currentAdjustingPayroll" :adjustment-types="adjustmentTypes" />
    </AdminLayout>
</template>
