<script setup lang="ts">
  import { computed, onMounted } from "vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
    CardFooter,
  } from "@/components/ui/card";
  import { Button } from "@/components/ui/button";
  import { useTransactionsStore } from "@/stores/transactions";
  import { formatCurrency } from "@/lib/utils";
  import { useRouter } from "vue-router";

  // Access the transactions store
  const transactionsStore = useTransactionsStore();
  const { totalIncome, totalExpenses, balance, loading, transactions } = transactionsStore;

  // Calculate balance history from transactions
  const balanceHistory = computed(() => {
    const now = new Date();
    const months = [];
    
    // Get last 6 months
    for (let i = 5; i >= 0; i--) {
      const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const monthName = month.toLocaleDateString('en-US', { month: 'short' });
      months.push({
        month: monthName,
        year: month.getFullYear(),
        monthIndex: month.getMonth(),
        balance: 0,
        income: 0,
        expenses: 0
      });
    }
    
    // Calculate balance for each month
    transactionsStore.transactions.forEach(transaction => {
      const txDate = new Date(transaction.date);
      const monthIndex = months.findIndex(m => 
        m.monthIndex === txDate.getMonth() && 
        m.year === txDate.getFullYear()
      );
      
      if (monthIndex !== -1) {
        if (transaction.type === 'income') {
          months[monthIndex].income += transaction.amount;
        } else {
          months[monthIndex].expenses += transaction.amount;
        }
        months[monthIndex].balance = months[monthIndex].income - months[monthIndex].expenses;
      }
    });

    // Ensure there's some data for visualization
    const maxBalance = Math.max(...months.map(m => Math.abs(m.balance)), 1000);
    return {
      months,
      maxBalance
    };
  });

  // Format balance with colors - neutral by default, red if negative
  const balanceClass = computed(() =>
    balance.value < 0 ? "text-red-500" : "text-gray-700",
  );

  onMounted(() => {
    transactionsStore.fetchTransactions();
  });
</script>

<template>
  <Card class="w-full shadow-sm hover:shadow transition-shadow duration-300">
    <CardHeader class="pb-2">
      <CardTitle class="text-xl font-bold flex items-center">
        <span class="mr-2">Balance Summary</span>
        <span v-if="loading" class="inline-block w-3 h-3 rounded-full bg-primary animate-pulse"></span>
      </CardTitle>
    </CardHeader>
    <CardContent>
      <div class="space-y-4">
        <!-- Summary Stats -->
        <div class="grid grid-cols-2 gap-4 pb-2">
          <!-- Income -->
          <div class="rounded-lg bg-green-50 p-3 transition-all">
            <div class="text-sm font-medium text-gray-500">Income</div>
            <div class="text-green-600 font-semibold text-lg mt-1">
              {{ formatCurrency(totalIncome) }}
            </div>
          </div>
          
          <!-- Expenses -->
          <div class="rounded-lg bg-red-50 p-3 transition-all">
            <div class="text-sm font-medium text-gray-500">Expenses</div>
            <div class="text-red-600 font-semibold text-lg mt-1">
              {{ formatCurrency(totalExpenses) }}
            </div>
          </div>
        </div>

        <div class="pt-4 border-t">
          <div class="flex justify-between items-center">
            <div class="text-sm font-bold">Current Balance</div>
            <div :class="balanceClass" class="text-xl font-bold flex items-center">
              {{ balance < 0 ? '-' : '' }}{{ formatCurrency(Math.abs(balance)) }}
              <span class="ml-1 text-xs" :class="balance < 0 ? 'text-red-400' : 'text-gray-500'">
                ({{ balance >= 0 ? '+' : '' }}{{ Math.round(balance / Math.max(totalIncome, 1) * 100) }}%)
              </span>
            </div>
          </div>
        </div>

        <!-- Balance History Chart -->
        <div class="mt-6">
          <h3 class="text-sm font-medium mb-2">Balance History</h3>
          
          <!-- No data message -->
          <div v-if="transactions.length === 0" class="text-center py-6 bg-gray-50 rounded-md border border-dashed border-gray-200">
            <p class="text-sm text-gray-500">No transaction data available</p>
            <router-link to="/add" class="text-xs text-primary hover:underline mt-1 inline-block">
              Add your first transaction
            </router-link>
          </div>
          
          <!-- Chart -->
          <div v-else class="h-32 flex items-end justify-between">
            <div
              v-for="(item, index) in balanceHistory.months"
              :key="index"
              class="flex flex-col items-center w-full group relative cursor-pointer">
              <div class="relative w-full h-24 flex flex-col justify-end items-center">
                <!-- Bar -->
                <div
                  class="w-8 rounded-t transition-all duration-500 ease-in-out hover:opacity-80"
                  :class="item.balance >= 0 ? 'bg-green-500/80' : 'bg-red-500/80'"
                  :style="{
                    height: `${Math.abs(item.balance) / (balanceHistory.maxBalance / 100)}%`,
                    minHeight: '4px'
                  }">
                </div>
                
                <!-- Tooltip with month data -->
                <div class="opacity-0 group-hover:opacity-100 absolute bottom-full mb-2 bg-gray-800 text-white text-xs rounded py-1 px-2 whitespace-nowrap z-10 shadow-md transition-opacity">
                  <div class="font-medium mb-1">{{ item.month }} {{ item.year }}</div>
                  <div>Income: {{ formatCurrency(item.income) }}</div>
                  <div>Expenses: {{ formatCurrency(item.expenses) }}</div>
                  <div class="mt-1 pt-1 border-t border-gray-700">
                    <span :class="item.balance >= 0 ? 'text-green-400' : 'text-red-400'">
                      Balance: {{ formatCurrency(item.balance) }}
                    </span>
                  </div>
                </div>
              </div>
              <span class="text-xs mt-1 text-gray-600">{{ item.month }}</span>
            </div>
          </div>
        </div>
      </div>
    </CardContent>
    <CardFooter>
      <router-link to="/reports" class="w-full">
        <Button variant="outline" size="sm" class="w-full hover:bg-primary/10 transition-colors">
          View Detailed Report
        </Button>
      </router-link>
    </CardFooter>
  </Card>
</template>
