import LoginClient from "@/app/login/login-client";
import { createAdminClient } from "@/lib/supabase-admin";
import { createClient } from "@/lib/supabase-server";
import { isOwnerUser } from "@/lib/owner-auth";
import DashboardClient from "./dashboard-client";

type AccessRow = {
  id: string;
  email: string;
  name: string | null;
  status: string | null;
  plan_name: string | null;
  expires_at: string | null;
  created_at: string | null;
};

export default async function OwnerHomePage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return <LoginClient />;
  }

  if (!isOwnerUser({ id: user.id, email: user.email })) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6 bg-slate-50">
        <div className="w-full max-w-lg rounded-2xl bg-white p-8 shadow-sm border border-slate-200 text-center">
          <h1 className="text-xl font-semibold text-slate-900">Acesso negado</h1>
          <p className="text-sm text-slate-500 mt-2">
            Seu usuário não tem permissão para acessar este painel.
          </p>
        </div>
      </div>
    );
  }

  const admin = createAdminClient();
  const now = new Date();
  const nowIso = now.toISOString();
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(now.getDate() - 30);
  const thirtyDaysAgoIso = thirtyDaysAgo.toISOString();

  // Parallel data fetching
  const [
    { count: totalCompanies },
    { data: activeAccessData },
    { count: totalQuotes },
    { count: totalOrders },
    { data: recentCompaniesData },
    { data: revenueData },
    { data: newUsersData },
    { data: allPaidOrdersData },
    { data: paymentsData },
  ] = await Promise.all([
    // 1. Total Companies
    admin.from("users_app").select("id", { count: "exact", head: true }),
    
    // 2. Active Access (for count and MMR/Annual)
    admin
      .from("users_app")
      .select("id, email, plan_name")
      .eq("status", "active")
      .or(`expires_at.is.null,expires_at.gte.${nowIso}`),
      
    // 3. Total Quotes
    admin.from("quotes").select("id", { count: "exact", head: true }),
    
    // 4. Total Orders
    admin.from("orders").select("id", { count: "exact", head: true }),
    
    // 5. Recent Companies
    admin
      .from("users_app")
      .select("id,email,name,status,plan_name,expires_at,created_at")
      .order("created_at", { ascending: false })
      .limit(5),

    // 6. Revenue Chart Data (Last 30 days)
    admin
      .from("orders")
      .select("created_at, total_amount, paid_amount")
      .eq("financial_status", "paid")
      .gte("created_at", thirtyDaysAgoIso)
      .order("created_at", { ascending: true }),

    // 7. New Users Chart Data (Last 30 days)
    admin
      .from("users_app")
      .select("created_at")
      .gte("created_at", thirtyDaysAgoIso)
      .order("created_at", { ascending: true }),

    // 8. Total Revenue (All time) - Summing all paid orders
    admin
      .from("orders")
      .select("total_amount, paid_amount")
      .eq("financial_status", "paid"),
      
    // 9. Legacy Payments Total (Fallback)
    admin.from("payments").select("total:amount.sum()"),
  ]);

  // Calculate MMR and Annual Revenue
  const activeUsers = activeAccessData || [];
  const activeAccess = activeUsers.length;
  
  let mmr = 0;
  let annualRevenue = 0;

  /* Quem assinou os planos novos pela rota oficial da Cakto paga 69,90 / 597;
     os planos antigos (webhook do LazzerPro) seguem em 37 / 147. */
  const { data: planosNovos } = await admin
    .from("assinaturas_cakto")
    .select("email, plano")
    .not("situacao", "in", "(reembolsada,contestada)");
  const planoNovoDoEmail = new Map(
    ((planosNovos as Array<{ email: string; plano: string }> | null) ?? []).map((linha) => [linha.email, linha.plano])
  );

  activeUsers.forEach((user) => {
    const plan = (user.plan_name || "").toLowerCase();
    const novo = planoNovoDoEmail.get(String(user.email || "").toLowerCase());
    if (novo === "mensal") {
      mmr += 69.9;
    } else if (novo === "anual") {
      annualRevenue += 597;
    } else if (plan.includes("mensal")) {
      mmr += 37.00;
    } else if (plan.includes("anual")) {
      annualRevenue += 147.00;
    }
  });

  // Calculate Total Revenue
  const paidOrders = (allPaidOrdersData as Array<{ total_amount?: number | null; paid_amount?: number | null }> | null) ?? [];
  const paidTotalFromOrders = paidOrders.reduce(
    (sum, order) => sum + Number(order.total_amount ?? order.paid_amount ?? 0),
    0
  );
  const paymentsTotal = Array.isArray(paymentsData)
    ? Number((paymentsData[0] as { total?: number | null } | null)?.total ?? 0)
    : 0;
  const totalRevenue = paidTotalFromOrders > 0 ? paidTotalFromOrders : paymentsTotal;

  // Process Chart Data
  const last30Days = Array.from({ length: 30 }, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() - (29 - i));
    return d.toISOString().split("T")[0]; // YYYY-MM-DD
  });

  // Revenue by Day
  const revenueByDay = (revenueData || []).reduce((acc, order) => {
    if (!order.created_at) return acc;
    const date = order.created_at.split("T")[0];
    const amount = Number(order.total_amount ?? order.paid_amount ?? 0);
    acc[date] = (acc[date] || 0) + amount;
    return acc;
  }, {} as Record<string, number>);

  const revenueChart = last30Days.map((date) => {
    const [, month, day] = date.split("-");
    return {
      date: `${day}/${month}`,
      amount: revenueByDay[date] || 0,
    };
  });

  // New Users by Day
  const usersByDay = (newUsersData || []).reduce((acc, user) => {
    if (!user.created_at) return acc;
    const date = user.created_at.split("T")[0];
    acc[date] = (acc[date] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  const newUsersChart = last30Days.map((date) => {
    const [, month, day] = date.split("-");
    return {
      date: `${day}/${month}`,
      count: usersByDay[date] || 0,
    };
  });

  const dashboardData = {
    stats: {
      totalCompanies: totalCompanies || 0,
      activeAccess: activeAccess || 0,
      totalQuotes: totalQuotes || 0,
      totalOrders: totalOrders || 0,
      totalRevenue,
      mmr,
      annualRevenue,
    },
    recentCompanies: (recentCompaniesData as AccessRow[]) || [],
    chartData: {
      revenue: revenueChart,
      newUsers: newUsersChart,
    },
  };

  /* Assinatura pela Cakto: o que precisa de olho. O relógio do admin tenta de
     novo sozinho; isto aparece quando ele ainda não conseguiu. */
  const [{ count: avisosComFalha }, { count: cancelamentosPendentes }] = await Promise.all([
    admin.from("subscription_webhook_events").select("id", { count: "exact", head: true }).eq("provider", "cakto").eq("status", "failed"),
    admin
      .from("assinaturas_cakto")
      .select("id", { count: "exact", head: true })
      .eq("cancelar_na_cakto", true)
      .is("cancelada_na_cakto_em", null)
      .lt("atualizada_em", new Date(now.getTime() - 15 * 60 * 1000).toISOString()),
  ]);
  const pendenciasCakto = (avisosComFalha ?? 0) + (cancelamentosPendentes ?? 0);

  return (
    <>
      {pendenciasCakto ? (
        <div className="mx-auto mt-4 max-w-6xl rounded-md border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-800">
          Assinatura pela Cakto: {avisosComFalha ?? 0} aviso(s) com falha e {cancelamentosPendentes ?? 0} cancelamento(s) pendente(s) há mais de 15 minutos. Abra a
          empresa para ver o detalhe e tentar de novo.
        </div>
      ) : null}
      <DashboardClient data={dashboardData} />
    </>
  );
}
