<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import Dialog from 'primevue/dialog';
import { Transaction } from '@/models/transaction';
import { TransactionService, TransactionFilters } from '@/services/transactions-service';
import { useSpaceStore } from '@/stores/spaceStore';
import { formatAmount, toDateOnly } from '@/utils/utils';
import ProgressSpinner from 'primevue/progressspinner';
import dayjs from 'dayjs';
import { TransactionKind } from '@/models/enums';

const props = defineProps<{
    visible: boolean;
    categoryId: number | null;
    categoryName: string;
    categoryIcon: string;
    startDate: Date;
    endDate: Date;
}>();

const emit = defineEmits<{
    'update:visible': [value: boolean];
}>();

const spaceStore = useSpaceStore();
const transactions = ref<Transaction[]>([]);
const isLoading = ref(false);

const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
});

const fetchCategoryTransactions = async () => {
    if (!props.categoryId || !spaceStore.selectedSpaceId) return;

    isLoading.value = true;
    try {
        const filters: TransactionFilters = {
            type: null,
            kind: TransactionKind.INSTANT,
            categoriesIds: [props.categoryId],
            dateFrom: toDateOnly(props.startDate),
            dateTo: toDateOnly(props.endDate),
            isDone: null,
            offset: 0,
            limit: 100,
            sorts: [{ "sortBy": "t.date", "sortDirection": "DESC" }, { "sortBy": "t.id", "sortDirection": "DESC" }]
        };

        transactions.value = await TransactionService.getTransactions(spaceStore.selectedSpaceId, filters);
    } catch (error) {
        console.error('Failed to fetch category transactions:', error);
    } finally {
        isLoading.value = false;
    }
};

watch(() => props.visible, (newVal) => {
    if (newVal && props.categoryId) {
        fetchCategoryTransactions();
    }
});

const getTransactionTypeColor = (type: string) => {
    return type === 'EXPENSE' ? 'text-red-600' : 'text-green-600';
};

const getTransactionTypeIcon = (type: string) => {
    return type === 'EXPENSE' ? 'pi pi-arrow-up-right' : 'pi pi-arrow-down-left';
};
</script>

<template>
    <Dialog v-model:visible="dialogVisible" :header="`${categoryIcon} ${categoryName}`" :modal="true"
        :style="{ width: '90vw', maxWidth: '600px' }" :dismissableMask="true">
        <div v-if="isLoading" class="flex justify-center py-8">
            <ProgressSpinner />
        </div>

        <div v-else-if="transactions.length === 0" class="text-center py-8 text-surface-500">
            No transactions found for this category
        </div>

        <div v-else class="flex flex-col gap-2 max-h-[60vh] overflow-y-auto custom-scrollbar">
            <div v-for="transaction in transactions" :key="transaction.id"
                class="flex items-center justify-between p-3 rounded-lg hover:bg-surface-50 dark:hover:bg-surface-800 transition-colors border border-surface-200 dark:border-surface-700">
                <div class="flex flex-col gap-1 flex-1">
                    <div class="flex items-center gap-2">
                        <i
                            :class="[getTransactionTypeIcon(transaction.type), getTransactionTypeColor(transaction.type)]"></i>
                        <span class="font-medium text-surface-900 dark:text-surface-0">
                            {{ transaction.comment || 'No description' }}
                        </span>
                    </div>
                    <span class="text-xs text-surface-500 dark:text-surface-400">
                        {{ dayjs(transaction.date).format('DD MMM YYYY') }}
                    </span>
                </div>

                <div class="flex items-center gap-1 font-semibold" :class="getTransactionTypeColor(transaction.type)">
                    <span>{{ transaction.type === 'EXPENSE' ? '-' : '+' }}</span>
                    <span>{{ formatAmount(transaction.amount) }}</span>
                    <span>₽</span>
                </div>
            </div>
        </div>
    </Dialog>
</template>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
    width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
    background-color: var(--surface-300);
    border-radius: 20px;
}

.dark .custom-scrollbar::-webkit-scrollbar-thumb {
    background-color: var(--surface-700);
}
</style>
