<script setup lang="ts">
import { Transaction } from '@/models/transaction';
import { computed } from 'vue';
import dayjs from 'dayjs';
import { formatAmount } from '@/utils/utils';
import { Checkbox } from 'primevue';
import { Divider } from 'primevue';
import { useRouter } from 'vue-router';
import { UpdateTransactionDTO } from '@/models/transaction';
import { useSpaceStore } from '@/stores/spaceStore';
import { TransactionService } from '@/services/transactions-service';
import { useToast } from 'primevue';

const toast = useToast()
const spaceStore = useSpaceStore()

const router = useRouter()


const props = defineProps<{
    transactions: Transaction[];
}>();
const emits = defineEmits(["set-tx-done"])

const upcomingTransactions = computed(() => {
    return props.transactions
        .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
        .slice(0, 5);
});

const formatDate = (date: string | Date) => {
    return dayjs(date).format('MMM D');
};

const getDaysUntilText = (date: string | Date) => {
    const days = dayjs(date).diff(dayjs(), 'day');
    if (days === 0) return 'Today';
    if (days === 1) return 'Tomorrow';
    if (days < 0) return 'Overdue';
    return `in ${days} days`;
};

const getAmountColor = (type: string) => {
    return type === 'INCOME' ? '!text-green-600 !dark:text-green-400' : '!text-red-600 !dark:text-red-400';
};

const setTransactionDone = async (transaction: Transaction): Promise<void> => {
    const updateTransaction = {
        type: transaction.type,
        kind: transaction.kind,
        categoryId: transaction.category.id,
        comment: transaction.comment,
        amount: transaction.amount,
        fees: 0,
        isDone: transaction.isDone,
        date: new Date(transaction.date),
    } as UpdateTransactionDTO
    try {
        await TransactionService.updateTransaction(spaceStore.selectedSpaceId as number, transaction.id, updateTransaction)
    } catch (error) {
        toast.add({
            severity: 'error',
            summary: 'Failed to update transactions.',
            detail: String(error),
            life: 3000,
        })
    }
}


</script>

<template>
    <div class="flex flex-col gap-0 ">
        <div class="flex flex-row justify-between items-end px-2">
            <span class="text-xl !font-semibold ">Upcoming transactions</span>
            <router-link to="/transactions" class="text-sm text-primary-600 dark:text-primary-400 hover:underline">View
                all</router-link>
        </div>
        <div class="flex card">
            <span v-if="transactions.length == 0">Looks like you haven't plan any transactions yet. <router-link
                    to="/transactions/create" class="!text-blue-400">Try to create some.</router-link></span>
            <div v-else v-for="key in transactions.keys()" :key="transactions[key].id"
                class="flex flex-col  w-full gap-0 pl-5  items-start justify-items-center font-bold "
                @click="router.push(`/transactions/${transactions[key].id}/edit`)">
                <div class="flex flex-row  w-full items-center gap-4">
                    <Checkbox v-model="transactions[key].isDone" binary class="text-3xl"
                        @change="setTransactionDone(transactions[key])">
                        {{ transactions[key].category.icon }}
                    </Checkbox>
                    <div class="flex !flex-row !justify-between !w-full"
                        @click="router.push(`/transactions/${transactions[key].id}/edit`)">
                        <div class="flex flex-row items-center gap-2">
                            <div class="flex flex-col !font-bold "> {{ transactions[key].comment }}
                                <div class="flex flex-row text-sm">{{ transactions[key].category.icon }}
                                    {{ transactions[key].category.name }}
                                </div>
                            </div>
                        </div>
                        <div class="flex flex-row gap-2 items-center !w-fit">
                            <div class="flex flex-col justify-between items-end !w-fit whitespace-nowrap shrink-0">
                                <span class="text-lg !font-bold">{{ formatAmount(transactions[key].amount) }} ₽</span>
                                <span class="text-sm !font-extralight"> {{ formatDate(transactions[key].date) }} {{
                                    getDaysUntilText(transactions[key].date) }}</span>
                            </div>
                            <i class="pi pi-angle-right !font-extralight" />
                        </div>
                    </div>
                </div>
                <Divider v-if="key + 1 !== transactions.length" class="!m-0 !py-3" />
            </div>
        </div>
    </div>
</template>
