<script setup lang="ts">
  import { ref, computed, onMounted, reactive } from "vue";
  import PageLayout from "@/components/PageLayout.vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
  } from "@/components/ui/card";
  import { Button } from "@/components/ui/button";
  import { useTransactionsStore } from "@/stores/transactions";
  import { useCategoriesStore } from "@/stores/categories";
  import { formatCurrency } from "@/lib/utils";
  import { PieChart as PieChartIcon, BarChart as BarChartIcon, Calendar } from "lucide-vue-next";
  import PieChart from "@/components/charts/PieChart.vue";
  import BarChart from "@/components/charts/BarChart.vue";
  import DoughnutChart from "@/components/charts/DoughnutChart.vue";

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

  // Active report type
  const activeReport = ref("overview"); // 'overview', 'byCategory', 'byMonth'

  // Date filters
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth();
  const selectedYear = ref(currentYear);
  const selectedMonth = ref(currentMonth);

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

  // Helper function to get transactions for selected period
  const getFilteredTransactions = () => {
    return transactionsStore.transactions.filter((transaction) => {
      const transactionDate = new Date(transaction.date);
      const year = transactionDate.getFullYear();
      const month = transactionDate.getMonth();

      return (
        year === selectedYear.value &&
        (activeReport.value === "byMonth"
          ? true
          : month === selectedMonth.value)
      );
    });
  };

  // Monthly summary data
  const monthlySummary = computed(() => {
    const filteredTransactions = getFilteredTransactions();

    const income = filteredTransactions
      .filter((t) => t.type === "income")
      .reduce((sum, t) => sum + t.amount, 0);

    const expenses = filteredTransactions
      .filter((t) => t.type === "expense")
      .reduce((sum, t) => sum + t.amount, 0);

    const savings = income - expenses;
    const savingsRate = income > 0 ? (savings / income) * 100 : 0;

    return {
      income,
      expenses,
      savings,
      savingsRate: savingsRate.toFixed(1),
      transactionCount: filteredTransactions.length,
    };
  });

  // Category breakdown data
  const categoryBreakdown = computed(() => {
    const filteredTransactions = getFilteredTransactions();
    const breakdown = {};

    // Group expenses by category
    filteredTransactions
      .filter((t) => t.type === "expense")
      .forEach((transaction) => {
        const categoryId = transaction.categoryId;
        if (!breakdown[categoryId]) {
          const category = categoriesStore.categories.find(
            (c) => c._id === categoryId,
          );
          breakdown[categoryId] = {
            categoryId,
            name: category ? category.name : "Unknown",
            amount: 0,
            percentage: 0,
            color: category?.color || "#cccccc",
          };
        }

        breakdown[categoryId].amount += transaction.amount;
      });

    // Calculate percentages
    const totalExpenses = Object.values(breakdown).reduce(
      (sum: number, item: any) => sum + item.amount,
      0,
    );
    Object.values(breakdown).forEach((item: any) => {
      item.percentage =
        totalExpenses > 0
          ? ((item.amount / totalExpenses) * 100).toFixed(1)
          : 0;
    });

    // Sort by amount (highest first)
    return Object.values(breakdown).sort(
      (a: any, b: any) => b.amount - a.amount,
    );
  });

  // Monthly trend data (simplified for the template)
  const monthlyTrend = computed(() => {
    const result = [];
    const months = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ];

    // Generate data for each month
    for (let i = 0; i < 12; i++) {
      const monthTransactions = transactionsStore.transactions.filter(
        (transaction) => {
          const date = new Date(transaction.date);
          return (
            date.getFullYear() === selectedYear.value && date.getMonth() === i
          );
        },
      );

      const income = monthTransactions
        .filter((t) => t.type === "income")
        .reduce((sum, t) => sum + t.amount, 0);

      const expenses = monthTransactions
        .filter((t) => t.type === "expense")
        .reduce((sum, t) => sum + t.amount, 0);

      result.push({
        month: months[i],
        income,
        expenses,
        savings: income - expenses,
      });
    }

    return result;
  });
  
  // Chart data for monthly trend
  const monthlyTrendChartData = computed(() => {
    return {
      labels: monthlyTrend.value.map(item => item.month),
      datasets: [
        {
          label: 'Income',
          data: monthlyTrend.value.map(item => item.income),
          backgroundColor: 'rgba(75, 192, 75, 0.6)',
          borderColor: 'rgba(75, 192, 75, 1)',
          borderWidth: 1
        },
        {
          label: 'Expenses',
          data: monthlyTrend.value.map(item => item.expenses),
          backgroundColor: 'rgba(255, 99, 132, 0.6)',
          borderColor: 'rgba(255, 99, 132, 1)',
          borderWidth: 1
        },
        {
          label: 'Savings',
          data: monthlyTrend.value.map(item => item.savings),
          backgroundColor: 'rgba(54, 162, 235, 0.6)',
          borderColor: 'rgba(54, 162, 235, 1)',
          borderWidth: 1
        }
      ]
    };
  });
  
  // Chart data for category breakdown
  const categoryChartData = computed(() => {
    return {
      labels: categoryBreakdown.value.map(item => item.name),
      datasets: [{
        data: categoryBreakdown.value.map(item => item.amount),
        backgroundColor: categoryBreakdown.value.map(item => item.color),
        borderColor: categoryBreakdown.value.map(item => item.color),
        hoverOffset: 4,
        borderWidth: 1
      }]
    };
  });
  
  // Budget usage doughnut chart data
  const budgetChartData = computed(() => {
    // For this example, we'll use a mock budget value of $2000
    // In a real app, you'd get this from user settings or another store
    const targetBudget = 2000;
    const spent = monthlySummary.value.expenses;
    const remaining = Math.max(0, targetBudget - spent);
    const percentage = Math.min(100, Math.round((spent / targetBudget) * 100));
    
    let statusColor = '#22c55e'; // green for < 70%
    if (percentage >= 90) {
      statusColor = '#ef4444'; // red for >= 90%
    } else if (percentage >= 70) {
      statusColor = '#f59e0b'; // amber for >= 70%
    }
    
    return {
      labels: ['Spent', 'Remaining'],
      datasets: [{
        data: [spent, remaining],
        backgroundColor: [statusColor, '#e5e7eb'],
        borderColor: ['transparent', 'transparent'],
        borderWidth: 0,
        cutout: '80%'
      }]
    };
  });

  // Function to switch between report types
  const setReportType = (type) => {
    activeReport.value = type;
  };

  const monthName = computed(() => {
    return new Date(selectedYear.value, selectedMonth.value).toLocaleString(
      "default",
      { month: "long" },
    );
  });
</script>

<template>
  <PageLayout header="Financial Reports">
    <!-- Report type selector -->
    <div class="mb-6 flex flex-wrap gap-2">
      <Button
        :variant="activeReport === 'overview' ? 'default' : 'outline'"
        @click="setReportType('overview')">
        <PieChartIcon class="mr-2 h-4 w-4" />
        Monthly Overview
      </Button>
      <Button
        :variant="activeReport === 'byCategory' ? 'default' : 'outline'"
        @click="setReportType('byCategory')">
        <BarChartIcon class="mr-2 h-4 w-4" />
        Spending by Category
      </Button>
      <Button
        :variant="activeReport === 'byMonth' ? 'default' : 'outline'"
        @click="setReportType('byMonth')">
        <Calendar class="mr-2 h-4 w-4" />
        Monthly Trend
      </Button>
    </div>

    <!-- Period selector -->
    <div class="mb-6 flex gap-3 items-center">
      <div>
        <select
          v-model="selectedMonth"
          class="border rounded p-1"
          v-if="activeReport !== 'byMonth'">
          <option value="0">January</option>
          <option value="1">February</option>
          <option value="2">March</option>
          <option value="3">April</option>
          <option value="4">May</option>
          <option value="5">June</option>
          <option value="6">July</option>
          <option value="7">August</option>
          <option value="8">September</option>
          <option value="9">October</option>
          <option value="10">November</option>
          <option value="11">December</option>
        </select>
      </div>
      <div>
        <select v-model="selectedYear" class="border rounded p-1">
          <option :value="currentYear - 2">{{ currentYear - 2 }}</option>
          <option :value="currentYear - 1">{{ currentYear - 1 }}</option>
          <option :value="currentYear">{{ currentYear }}</option>
        </select>
      </div>
    </div>

    <!-- Monthly Overview Report -->
    <div v-if="activeReport === 'overview'" class="grid md:grid-cols-2 gap-6">
      <Card>
        <CardHeader>
          <CardTitle>{{ monthName }} Summary</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <div class="text-sm text-gray-500">Income</div>
                <div class="text-xl font-bold text-green-500">
                  {{ formatCurrency(monthlySummary.income) }}
                </div>
              </div>
              <div>
                <div class="text-sm text-gray-500">Expenses</div>
                <div class="text-xl font-bold text-red-500">
                  {{ formatCurrency(monthlySummary.expenses) }}
                </div>
              </div>
            </div>

            <div class="pt-3 border-t">
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <div class="text-sm text-gray-500">Savings</div>
                  <div
                    class="text-xl font-bold"
                    :class="
                      monthlySummary.savings >= 0
                        ? 'text-green-500'
                        : 'text-red-500'
                    ">
                    {{ formatCurrency(monthlySummary.savings) }}
                  </div>
                </div>
                <div>
                  <div class="text-sm text-gray-500">Savings Rate</div>
                  <div class="text-xl font-bold">
                    {{ monthlySummary.savingsRate }}%
                  </div>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Budget comparison chart -->
      <Card>
        <CardHeader>
          <CardTitle>Budget Comparison</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="relative h-60">
            <DoughnutChart 
              :chartData="budgetChartData"
              :chartOptions="{
                plugins: {
                  tooltip: {
                    callbacks: {
                      label: (context) => {
                        const value = context.parsed;
                        const label = context.label;
                        return `${label}: ${formatCurrency(value)}`;
                      }
                    }
                  },
                  legend: {
                    display: false
                  }
                }
              }"
            />
            <!-- Center text with percentage -->
            <div class="absolute inset-0 flex flex-col items-center justify-center">
              <span class="text-4xl font-bold">
                {{ Math.min(100, Math.round((monthlySummary.expenses / 2000) * 100)) }}%
              </span>
              <span class="text-sm text-gray-500">of monthly budget</span>
            </div>
          </div>
          <div class="mt-4 flex justify-between text-sm">
            <div>
              <div class="text-gray-500">Monthly Budget</div>
              <div class="font-medium">{{ formatCurrency(2000) }}</div>
            </div>
            <div>
              <div class="text-gray-500">Spent</div>
              <div class="font-medium">{{ formatCurrency(monthlySummary.expenses) }}</div>
            </div>
            <div>
              <div class="text-gray-500">Remaining</div>
              <div class="font-medium">{{ formatCurrency(Math.max(0, 2000 - monthlySummary.expenses)) }}</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>

    <!-- Category Breakdown Report -->
    <div v-if="activeReport === 'byCategory'">
      <Card>
        <CardHeader>
          <CardTitle>Spending by Category</CardTitle>
        </CardHeader>
        <CardContent>
          <div v-if="categoryBreakdown.length === 0" class="text-center py-6">
            <p class="text-gray-500">
              No expense data available for this period
            </p>
          </div>

          <div v-else class="space-y-6">
            <!-- Pie chart for category spending -->
            <div class="h-72">
              <PieChart 
                :chartData="categoryChartData"
                :chartOptions="{
                  plugins: {
                    tooltip: {
                      callbacks: {
                        label: (context) => {
                          const value = context.parsed;
                          const label = context.label;
                          const percentage = categoryBreakdown.value[context.dataIndex]?.percentage;
                          return `${label}: ${formatCurrency(value)} (${percentage}%)`;
                        }
                      }
                    }
                  }
                }"
              />
            </div>

            <!-- Category breakdown table -->
            <div class="space-y-3">
              <div
                v-for="category in categoryBreakdown"
                :key="category.categoryId"
                class="flex items-center py-2">
                <div
                  class="w-3 h-3 rounded-full mr-3"
                  :style="{ backgroundColor: category.color }"></div>
                <div class="flex-grow">{{ category.name }}</div>
                <div class="font-medium mr-4">
                  {{ formatCurrency(category.amount) }}
                </div>
                <div class="text-gray-500 w-16 text-right">
                  {{ category.percentage }}%
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>

    <!-- Monthly Trend Report -->
    <div v-if="activeReport === 'byMonth'">
      <Card>
        <CardHeader>
          <CardTitle>Monthly Income & Expenses ({{ selectedYear }})</CardTitle>
        </CardHeader>
        <CardContent>
          <!-- Monthly trend bar chart -->
          <div class="h-80">
            <BarChart 
              :chartData="monthlyTrendChartData" 
            />
          </div>

          <!-- Monthly data table -->
          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr class="border-b">
                  <th class="py-2 text-left">Month</th>
                  <th class="py-2 text-right">Income</th>
                  <th class="py-2 text-right">Expenses</th>
                  <th class="py-2 text-right">Savings</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="month in monthlyTrend"
                  :key="month.month"
                  class="border-b">
                  <td class="py-2">{{ month.month }}</td>
                  <td class="py-2 text-right text-green-600">
                    {{ formatCurrency(month.income) }}
                  </td>
                  <td class="py-2 text-right text-red-600">
                    {{ formatCurrency(month.expenses) }}
                  </td>
                  <td
                    class="py-2 text-right"
                    :class="
                      month.savings >= 0 ? 'text-green-600' : 'text-red-600'
                    ">
                    {{ formatCurrency(month.savings) }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  </PageLayout>
</template>
