<script setup lang="ts">
  import { onMounted, ref, computed } from "vue";
  import PageLayout from "../components/PageLayout.vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
    CardFooter,
  } from "@/components/ui/card";
  import { Button } from "@/components/ui/button";
  import { useTransactionsStore } from "@/stores/transactions";
  import { useCategoriesStore } from "@/stores/categories";
  import { useAuthStore } from "@/stores/auth";
  import { formatCurrency } from "@/lib/utils";
  import BalanceSummary from "@/components/BalanceSummary.vue";

  // Initialize stores
  const transactionsStore = useTransactionsStore();
  const categoriesStore = useCategoriesStore();
  const authStore = useAuthStore();

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

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

  onMounted(async () => {
    // Fetch transactions and categories
    await Promise.all([
      transactionsStore.fetchTransactions(),
      categoriesStore.fetchCategories(),
    ]);
  });
</script>

<template>
  <PageLayout header="Dashboard">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- Balance Summary -->
      <div class="lg:col-span-2">
        <BalanceSummary />
      </div>

      <!-- Quick Actions -->
      <Card>
        <CardHeader>
          <CardTitle>Quick Actions</CardTitle>
        </CardHeader>
        <CardContent class="space-y-4">
          <router-link to="/add" class="w-full block">
            <Button class="w-full" variant="default">Add New Transaction</Button>
          </router-link>
          <router-link to="/reports" class="w-full block">
            <Button class="w-full" variant="outline">View Reports</Button>
          </router-link>
          <router-link to="/categories" class="w-full block">
            <Button class="w-full" variant="outline">Manage Categories</Button>
          </router-link>
          <router-link to="/settings" class="w-full block">
            <Button class="w-full" variant="outline">Budget Settings</Button>
          </router-link>
        </CardContent>
      </Card>

      <!-- Recent Transactions -->
      <Card class="lg:col-span-3">
        <CardHeader>
          <CardTitle>Recent Transactions</CardTitle>
        </CardHeader>
        <CardContent>
          <div v-if="!authStore.isAuthenticated" class="text-center py-8">
            <p class="text-gray-500">Please log in to view your transactions</p>
            <router-link to="/login">
              <Button class="mt-4">Log In</Button>
            </router-link>
          </div>
          <div
            v-else-if="recentTransactions.length === 0"
            class="text-center py-8">
            <p class="text-gray-500">No transactions yet</p>
            <router-link to="/add">
              <Button class="mt-4">Add Your First Transaction</Button>
            </router-link>
          </div>
          <div v-else>
            <div class="divide-y">
              <div
                v-for="transaction in recentTransactions"
                :key="transaction._id"
                class="py-3">
                <div class="flex justify-between items-center">
                  <div>
                    <p class="font-medium">
                      {{
                        transaction.description ||
                        getCategoryName(transaction.categoryId)
                      }}
                    </p>
                    <p class="text-sm text-gray-500">
                      {{ new Date(transaction.date).toLocaleDateString() }}
                    </p>
                  </div>
                  <div
                    :class="
                      transaction.type === 'expense'
                        ? 'text-red-500'
                        : 'text-green-500'
                    "
                    class="font-bold">
                    {{ transaction.type === "expense" ? "-" : "+"
                    }}{{ formatCurrency(transaction.amount) }}
                  </div>
                </div>
              </div>
            </div>

            <div class="mt-4 text-center">
              <router-link to="/transactions">
                <Button variant="ghost" size="sm">View All Transactions</Button>
              </router-link>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  </PageLayout>
</template>
