<script setup lang="ts">
import { Head } from '@inertiajs/vue3';
import { ArrowDownCircle, ArrowUpCircle, Wallet } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import CashTransactionFormModal from '@/components/admin/finance/cash/CashTransactionFormModal.vue';
import { createColumns } from '@/components/admin/finance/cash/columns';
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 { useDataTableQuery, useDataTableQuerySync } from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { CashAccount, CashTransactionListItem, PaginatedCashTransactions } from '@/types/cash';
import type { DataTableSort } from '@/types/data-table';

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

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

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

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 pagination = computed(() => ({
    currentPage: props.transactions.current_page,
    perPage: props.transactions.per_page,
    lastPage: props.transactions.last_page,
    total: props.transactions.total,
}));

function openCreateModal(mode: 'deposit' | '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('deposit')">
                    <ArrowDownCircle class="size-4" />
                    Setor Kas
                </Button>
                <Button v-if="can('cash.withdraw')" variant="outline" @click="openCreateModal('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"
                    @sort-change="setSort" @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>
