"use server";

import { createClient } from "@/lib/supabase/server";

export async function getDashboardStats() {
  const supabase = await createClient();
  const today = new Date().toISOString().slice(0, 10);
  const monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10);

  const [patients, todayAppts, monthInvoices, products, lowStock] = await Promise.all([
    supabase.from("patients").select("*", { count: "exact", head: true }).eq("is_active", true),
    supabase.from("appointments").select("*", { count: "exact", head: true }).gte("starts_at", `${today}T00:00:00`).lte("starts_at", `${today}T23:59:59`),
    supabase.from("invoices").select("total, payment_status").gte("created_at", `${monthStart}T00:00:00`),
    supabase.from("products").select("*", { count: "exact", head: true }).eq("is_active", true),
    supabase.from("products").select("*, stock:inventory_stock(current_stock)").eq("is_active", true),
  ]);

  const monthRevenue = (monthInvoices.data || [])
    .filter((i: any) => i.payment_status === "paid")
    .reduce((sum: number, i: any) => sum + Number(i.total), 0);

  const lowStockCount = (lowStock.data || []).filter((p: any) => {
    const stock = p.stock?.[0]?.current_stock || 0;
    return stock <= p.min_stock && p.min_stock > 0;
  }).length;

  return {
    totalPatients: patients.count || 0,
    todayAppointments: todayAppts.count || 0,
    monthRevenue,
    totalProducts: products.count || 0,
    lowStockCount,
    totalInvoices: (monthInvoices.data || []).length,
  };
}

export async function getRevenueChart() {
  const supabase = await createClient();
  const sixMonthsAgo = new Date();
  sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 5);
  sixMonthsAgo.setDate(1);

  const { data: invoices } = await supabase
    .from("invoices")
    .select("total, payment_status, created_at")
    .gte("created_at", sixMonthsAgo.toISOString())
    .eq("payment_status", "paid");

  const months: Record<string, number> = {};
  const now = new Date();
  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
    months[key] = 0;
  }

  (invoices || []).forEach((inv: any) => {
    const key = inv.created_at.slice(0, 7);
    if (months[key] !== undefined) months[key] += Number(inv.total);
  });

  const monthNames = ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"];
  return Object.entries(months).map(([key, value]) => ({
    month: monthNames[parseInt(key.split("-")[1]) - 1],
    revenue: Math.round(value * 100) / 100,
  }));
}

export async function getUpcomingAppointments() {
  const supabase = await createClient();
  const now = new Date().toISOString();
  const endOfDay = new Date();
  endOfDay.setHours(23, 59, 59, 999);

  const { data } = await supabase
    .from("appointments")
    .select("*, patient:patients(id, first_name, last_name, phone), doctor:users(id, full_name, color)")
    .gte("starts_at", now)
    .lte("starts_at", endOfDay.toISOString())
    .in("status", ["scheduled", "confirmed"])
    .order("starts_at")
    .limit(5);

  return data || [];
}

export async function getRecentPatients() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("patients")
    .select("id, first_name, last_name, phone, created_at")
    .eq("is_active", true)
    .order("created_at", { ascending: false })
    .limit(5);
  return data || [];
}
