<script setup lang="ts">
import { Head } from '@inertiajs/vue3';
import { ArrowDownCircle, ArrowUpCircle, Wallet } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useCan } from '@/composables/useCan';
import { CashReferenceType } from '@/constants/cash-reference-type';
import { CashTransactionType } from '@/constants/cash-transaction-type';
import { useDataTableQuery, useDataTableQuerySync } from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { CashAccount, CashTransactionListItem, PaginatedCashTransactions } from '@/types/cash';
import type { DataTableFilterDef, DataTableSort } from '@/types/data-table';
import CashTransactionFormModal from './form/CashTransactionFormModal.vue';
import { createColumns } from './table/columns';
import { index } from '@/routes/admin/finance/cash';

const props = defineProps<{
    cashAccount: CashAccount;
    transactions: PaginatedCashTransactions;
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
        reference_type?: string;
    };
}>();

const { can } = useCan();
const search = ref(props.filters.search ?? '');
const formModalOpen = ref(false);
const formModalMode = ref<'deposit' | 'withdrawal'>(CashTransactionType.DEPOSIT);
const editingTransaction = ref<CashTransactionListItem | null>(null);

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

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

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

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: 'reference_type',
        label: 'Sumber',
        type: 'select',
        options: [
            { value: CashReferenceType.MANUAL, label: 'Setor/Tarik Kas' },
            { value: CashReferenceType.EXPENSE, label: 'Pengeluaran' },
            { value: CashReferenceType.EMPLOYEE_ADVANCE, label: 'Kasbon Pegawai' },
            { value: CashReferenceType.PAYROLL, label: 'Gaji Pegawai' },
            { value: CashReferenceType.ORDER, label: 'Pesanan' },
        ],
    },
]);

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

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

function openCreateModal(mode: typeof CashTransactionType.DEPOSIT | typeof CashTransactionType.WITHDRAWAL) {
    editingTransaction.value = null;
    formModalMode.value = mode;
    formModalOpen.value = true;
}

function openEditModal(transaction: CashTransactionListItem) {
    editingTransaction.value = transaction;
    formModalOpen.value = true;
}

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

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

<template>

    <Head title="Kas Toko" />

    <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">
                    {{ cashAccount.name }}
                </h2>
            </div>

            <div class="flex shrink-0 items-center gap-2 self-start sm:self-center">
                <Button v-if="can('cash.deposit')" variant="outline" @click="openCreateModal(CashTransactionType.DEPOSIT)">
                    <ArrowDownCircle class="size-4" />
                    Setor Kas
                </Button>
                <Button v-if="can('cash.withdraw')" variant="outline" @click="openCreateModal(CashTransactionType.WITHDRAWAL)">
                    <ArrowUpCircle class="size-4" />
                    Tarik Kas
                </Button>
            </div>
        </div>

        <Card>
            <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle class="text-sm font-medium text-muted-foreground">
                    Saldo Saat Ini
                </CardTitle>
                <Wallet class="size-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div class="text-3xl font-bold tracking-tight">
                    {{ cashAccount.balance_formatted }}
                </div>
            </CardContent>
        </Card>

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

        <CashTransactionFormModal v-if="can('cash.deposit') || can('cash.withdraw') || can('cash.update')"
            v-model:open="formModalOpen" :transaction="editingTransaction" :mode="formModalMode" />
    </AdminLayout>
</template>
