<script setup lang="ts">

import Button from "primevue/button";
import Checkbox from "primevue/checkbox";
import {computed, onMounted, PropType, ref} from "vue";
import {Transaction} from "@/models/Transaction";
import {Category, CategoryType} from "@/models/Category";
import {getCategories, getCategoryTypes} from "@/services/categoryService";
import { updateTransactionRequest} from "@/services/transactionService";
import {formatAmount, formatDate} from "@/utils/utils";
import TransactionForm from "@/components/transactions/TransactionForm.vue";
import {useToast} from "primevue/usetoast";


const props = defineProps(
    {
      transaction: {
        type: Object as PropType<Transaction>,
        required: true,
      },
      isList: {
        type: Boolean,
        required: true,
      },
      transactions: {
        type: Array as () => Array<Transaction>,
        required: false
      }
    }
)
const emits = defineEmits(['open-drawer', 'transaction-checked', 'transaction-updated', 'delete-transaction'])



const setIsDoneTrue = async () => {
  setTimeout(async () => {

    await updateTransactionRequest(props.transaction)
    emits('transaction-updated')
  }, 20);
  // showedTransaction.value.isDone = !showedTransaction.value.isDone;
}

const toast = useToast();
const drawerOpened = ref(false)
const toggleDrawer = () => {
  if (props.transaction?.parentId) {
    toast.add({
      severity: 'warn',
      summary: 'Транзакцию нельзя изменить!',
      detail: 'Транзакции созданные из плана не могут быть изменены.',
      life: 3000
    });

  } else {

    if (drawerOpened.value) {
      drawerOpened.value = false;
    }
    drawerOpened.value = !drawerOpened.value
    emits('open-drawer', props.transaction)
  }
}

const transactionUpdate = () => {

  emits('transaction-updated')
}

const isPlanned = computed(() => {
  return props.transaction?.type.code === "PLANNED"
})


const entireCategories = ref<Category[]>([])
const expenseCategories = ref<Category[]>([])
const incomeCategories = ref<Category[]>([])
const fetchCategories = async () => {
  try {
    const response = await getCategories();
    entireCategories.value = response.data
    expenseCategories.value = response.data.filter((category: Category) => category.type.code === 'EXPENSE');
    incomeCategories.value = response.data.filter((category: Category) => category.type.code === 'INCOME');
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
}


const categoryTypes = ref<CategoryType[]>([]);
const selectedCategoryType = ref<CategoryType | null>(null);
const fetchCategoryTypes = async () => {

  try {
    const response = await getCategoryTypes();
    categoryTypes.value = response.data;
    selectedCategoryType.value = categoryTypes.value.find((category: CategoryType) => category.code === 'EXPENSE');
  } catch (error) {
    console.error('Error fetching category types:', error);
  }
};

const closeDrawer = () => {
  drawerOpened.value = false;
}


onMounted(async () => {
  // await fetchCategories();
  // await fetchCategoryTypes()


})

</script>

<template>
  <div :class="
          props.isList ? ' bg-gradient-to-r shadow-lg  border-2 gap-5 p-2 rounded-xl me-5'  : 'border-b pb-2'
"
       class="flex  bg-white  min-w-fit  max-h-fit flex-row items-center  gap-4 w-full ">
    <div>
      <p v-if="transaction.type.code=='INSTANT' || props.isList"
         class="text-6xl font-bold text-gray-700 dark:text-gray-400">
        {{ transaction.category.icon }}
      </p>

      <Checkbox v-model="transaction.isDone" v-else-if="transaction.type.code=='PLANNED' && !props.isList"
                :binary="true"
                @click="setIsDoneTrue"/>

    </div>
    <button class="flex flex-row  items-center p-x-4  justify-between w-full " @click="toggleDrawer">

      <div class="flex flex-col items-start justify-items-start">
        <p :class="transaction.isDone && isPlanned && !props.isList ? 'line-through' : ''" class="font-bold">{{
            transaction.comment
          }}</p>
        <p :class="transaction.isDone && isPlanned && !props.isList ? 'line-through' : ''" class="font-light">
          {{ isPlanned ? transaction.category.icon : '' }} {{
            transaction.category.name
          }} |
          {{ formatDate(transaction.date) }}</p>
      </div>
      <div
          :class="transaction.category.type.code == 'EXPENSE' ? 'text-red-700' : 'text-green-700' &&  transaction.isDone  && isPlanned ? 'line-through' : ''"
          class="text-lg line-clamp-1 ">

        {{ formatAmount(transaction.amount) }} ₽


      </div>

    </button>
  </div>
  <div>


    <TransactionForm v-if="drawerOpened" :visible="drawerOpened" :transaction="transaction"
                     @close-drawer="closeDrawer" @transaction-updated="transactionUpdate"
                     @delete-transaction="transactionUpdate"
                     @create-transaction="transactionUpdate"/>
  </div>

</template>

<style scoped>

</style>