import { createClient } from "@/lib/supabase/server";
import { DashboardView } from "@/components/dashboard/dashboard-view";

export default async function DashboardPage() {
  const supabase = createClient();
  const {
    data: { user }
  } = await supabase.auth.getUser();
  if (!user) return null;

  const now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10);
  const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1).toISOString().slice(0, 10);
  const endOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0).toISOString().slice(0, 10);

  const [profileRes, expensesRes, lastMonthExpensesRes, goalsRes, subsRes, recentRes] = await Promise.all([
    supabase.from("profiles").select("*").eq("id", user.id).single(),
    supabase.from("expenses").select("*").eq("user_id", user.id).gte("occurred_on", startOfMonth),
    supabase
      .from("expenses")
      .select("amount")
      .eq("user_id", user.id)
      .gte("occurred_on", startOfLastMonth)
      .lte("occurred_on", endOfLastMonth),
    supabase.from("goals").select("*").eq("user_id", user.id).order("created_at", { ascending: false }).limit(3),
    supabase
      .from("subscriptions")
      .select("*")
      .eq("user_id", user.id)
      .order("next_payment_date", { ascending: true })
      .limit(5),
    supabase.from("expenses").select("*").eq("user_id", user.id).order("occurred_on", { ascending: false }).limit(5)
  ]);

  const profile = profileRes.data;
  const expenses = expensesRes.data ?? [];
  const lastMonthTotal = (lastMonthExpensesRes.data ?? []).reduce((sum, e) => sum + Number(e.amount), 0);
  const thisMonthTotal = expenses.reduce((sum, e) => sum + Number(e.amount), 0);
  const monthlyIncome = Number(profile?.monthly_income ?? 0);

  const byCategory: Record<string, number> = {};
  for (const e of expenses) {
    byCategory[e.category] = (byCategory[e.category] ?? 0) + Number(e.amount);
  }

  return (
    <DashboardView
      firstName={profile?.first_name ?? null}
      currency={profile?.currency ?? "PLN"}
      monthlyIncome={monthlyIncome}
      thisMonthTotal={thisMonthTotal}
      lastMonthTotal={lastMonthTotal}
      byCategory={byCategory}
      goals={goalsRes.data ?? []}
      subscriptions={subsRes.data ?? []}
      recentExpenses={recentRes.data ?? []}
    />
  );
}
