<script setup lang="ts">
  import { ref, onMounted, computed } from "vue";
  import { useRouter } from "vue-router";
  import PageLayout from "@/components/PageLayout.vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
  } from "@/components/ui/card";
  import { useTransactionsStore } from "@/stores/transactions";
  import { useCategoriesStore } from "@/stores/categories";
  import { formatCurrency, formatDate } from "@/lib/utils";
  import { Input } from "@/components/ui/input";
  import { Button } from "@/components/ui/button";
  import {
    Search,
    ArrowUpDown,
    Filter,
    Edit,
    Trash2,
    Loader2,
    Plus,
  } from "lucide-vue-next";

  // Initialize stores and router
  const transactionsStore = useTransactionsStore();
  const categoriesStore = useCategoriesStore();
  const router = useRouter();

  // Local state
  const searchQuery = ref("");
  const sortBy = ref("date");
  const sortOrder = ref("desc");
  const filterType = ref("all"); // 'all', 'income', or 'expense'
  const isDeleting = ref(false);
  const deletingId = ref<string | null>(null);

  // Load data on component mount
  onMounted(async () => {
    await Promise.all([
      transactionsStore.fetchTransactions(),
      categoriesStore.fetchCategories(),
    ]);
  });

  // Get category name by ID
  const getCategoryName = (categoryId: string) => {
    const category = categoriesStore.categories.find(
      (c) => c._id === categoryId,
    );
    return category ? category.name : "Unknown";
  };

  // Filtered and sorted transactions
  const filteredTransactions = computed(() => {
    let result = [...transactionsStore.transactions];

    // Apply type filter
    if (filterType.value !== "all") {
      result = result.filter((t) => t.type === filterType.value);
    }

    // Apply search filter
    if (searchQuery.value.trim()) {
      const query = searchQuery.value.toLowerCase();
      result = result.filter((t) => {
        return (
          t.description?.toLowerCase().includes(query) ||
          getCategoryName(t.categoryId).toLowerCase().includes(query)
        );
      });
    }

    // Apply sorting
    result.sort((a, b) => {
      let compareResult = 0;

      switch (sortBy.value) {
        case "date":
          compareResult =
            new Date(a.date).getTime() - new Date(b.date).getTime();
          break;
        case "amount":
          compareResult = a.amount - b.amount;
          break;
        case "category":
          compareResult = getCategoryName(a.categoryId).localeCompare(
            getCategoryName(b.categoryId),
          );
          break;
        default:
          compareResult = 0;
      }

      return sortOrder.value === "asc" ? compareResult : -compareResult;
    });

    return result;
  });

  // Toggle sort order
  const toggleSort = (field: string) => {
    if (sortBy.value === field) {
      sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
    } else {
      sortBy.value = field;
      sortOrder.value = "desc";
    }
  };

  // Edit a transaction
  const editTransaction = (id: string) => {
    router.push(`/edit/${id}`);
  };

  // Delete a transaction
  const confirmDelete = async (id: string) => {
    if (confirm("Are you sure you want to delete this transaction?")) {
      deletingId.value = id;
      isDeleting.value = true;

      try {
        await transactionsStore.deleteTransaction(id);
      } catch (error) {
        console.error("Error deleting transaction:", error);
      } finally {
        isDeleting.value = false;
        deletingId.value = null;
      }
    }
  };
</script>

<template>
  <PageLayout header="Transactions">
    <div class="space-y-4">
      <!-- Filters and search -->
      <div class="flex flex-col sm:flex-row gap-4">
        <div class="relative flex-grow">
          <Input
            type="text"
            v-model="searchQuery"
            placeholder="Search transactions..."
            class="pl-10" />
          <Search
            class="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
        </div>

        <div class="flex gap-2">
          <Button
            variant="outline"
            :class="{ 'bg-primary/10': filterType === 'all' }"
            @click="filterType = 'all'">
            All
          </Button>
          <Button
            variant="outline"
            :class="{ 'bg-primary/10': filterType === 'income' }"
            @click="filterType = 'income'">
            Income
          </Button>
          <Button
            variant="outline"
            :class="{ 'bg-primary/10': filterType === 'expense' }"
            @click="filterType = 'expense'">
            Expenses
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader class="flex flex-row items-center justify-between">
          <CardTitle class="text-xl">Transaction History</CardTitle>
          <Button
            variant="default"
            size="sm"
            to="/add"
            class="flex items-center">
            <Plus class="mr-1 h-4 w-4" />
            Add New
          </Button>
        </CardHeader>
        <CardContent>
          <div v-if="transactionsStore.loading" class="text-center py-8">
            <p>Loading transactions...</p>
          </div>

          <div
            v-else-if="filteredTransactions.length === 0"
            class="text-center py-8">
            <p class="text-gray-500">No transactions found</p>
            <Button class="mt-4" to="/add">Add Transaction</Button>
          </div>

          <div v-else>
            <!-- Table header -->
            <div
              class="grid grid-cols-12 gap-4 py-3 px-4 font-medium text-sm border-b">
              <div
                class="col-span-3 sm:col-span-2 flex items-center cursor-pointer"
                @click="toggleSort('date')">
                Date
                <ArrowUpDown class="ml-1 h-4 w-4" />
              </div>
              <div
                class="col-span-4 sm:col-span-3 flex items-center cursor-pointer"
                @click="toggleSort('category')">
                Category
                <ArrowUpDown class="ml-1 h-4 w-4" />
              </div>
              <div class="col-span-3 sm:col-span-4 hidden sm:block">
                Description
              </div>
              <div
                class="col-span-3 sm:col-span-2 flex items-center justify-end cursor-pointer"
                @click="toggleSort('amount')">
                Amount
                <ArrowUpDown class="ml-1 h-4 w-4" />
              </div>
              <div class="col-span-2 sm:col-span-1 text-center">Actions</div>
            </div>

            <!-- Table body -->
            <div class="divide-y">
              <div
                v-for="transaction in filteredTransactions"
                :key="transaction._id"
                class="grid grid-cols-12 gap-4 py-4 px-4 hover:bg-gray-50 transition-colors">
                <div class="col-span-3 sm:col-span-2 text-sm text-gray-600">
                  {{ formatDate(transaction.date, "short") }}
                </div>
                <div class="col-span-4 sm:col-span-3">
                  {{ getCategoryName(transaction.categoryId) }}
                </div>
                <div class="col-span-3 sm:col-span-4 hidden sm:block text-sm">
                  {{ transaction.description || "-" }}
                </div>
                <div
                  class="col-span-3 sm:col-span-2 font-medium text-right"
                  :class="
                    transaction.type === 'income'
                      ? 'text-green-500'
                      : 'text-red-500'
                  ">
                  {{ transaction.type === "income" ? "+" : "-"
                  }}{{ formatCurrency(transaction.amount) }}
                </div>
                <div
                  class="col-span-2 sm:col-span-1 flex justify-end items-center gap-2">
                  <button
                    @click="editTransaction(transaction._id!)"
                    class="p-1 text-gray-500 hover:text-blue-500 transition-colors"
                    title="Edit transaction">
                    <Edit class="h-4 w-4" />
                  </button>
                  <button
                    @click="confirmDelete(transaction._id!)"
                    class="p-1 text-gray-500 hover:text-red-500 transition-colors"
                    :disabled="isDeleting && deletingId === transaction._id"
                    title="Delete transaction">
                    <Loader2
                      v-if="isDeleting && deletingId === transaction._id"
                      class="h-4 w-4 animate-spin" />
                    <Trash2 v-else class="h-4 w-4" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  </PageLayout>
</template>
