import type { Metadata } from "next";
import { db, users, recipes, userUsage, supportTickets, featureUpgradeClicks, gte, sql } from "@epicure/db";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { BarChart } from "@/components/admin/charts/bar-chart";
import { TimeSeriesChart } from "@/components/admin/charts/time-series-chart";
import { requireFullAdminPage } from "@/lib/require-admin-page";
import { FEATURE_DEFINITIONS } from "@/lib/feature-flags";

export const metadata: Metadata = {};

const DAYS = 30;

function lastNDays(n: number): string[] {
  const out: string[] = [];
  const now = new Date();
  for (let i = n - 1; i >= 0; i--) {
    const d = new Date(now);
    d.setDate(d.getDate() - i);
    out.push(d.toISOString().slice(0, 10));
  }
  return out;
}

function formatShortDate(d: string) {
  const date = new Date(`${d}T00:00:00Z`);
  return date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
}

function lastNMonths(n: number): string[] {
  const out: string[] = [];
  const now = new Date();
  for (let i = n - 1; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    out.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
  }
  return out;
}

export default async function AdminInsightsPage() {
  await requireFullAdminPage();
  const since = new Date();
  since.setDate(since.getDate() - DAYS);

  // Promise.allSettled, not all — six independent aggregate queries feeding
  // six independent charts; one query breaking (e.g. a table that's empty
  // in a fresh install) shouldn't take down every chart on the page.
  const results = await Promise.allSettled([
    db
      .select({ day: sql<string>`to_char(${users.createdAt}, 'YYYY-MM-DD')`.as("day"), n: sql<number>`count(*)::int` })
      .from(users)
      .where(gte(users.createdAt, since))
      .groupBy(sql`to_char(${users.createdAt}, 'YYYY-MM-DD')`),
    db
      .select({
        day: sql<string>`to_char(${recipes.createdAt}, 'YYYY-MM-DD')`.as("day"),
        aiGenerated: recipes.aiGenerated,
        n: sql<number>`count(*)::int`,
      })
      .from(recipes)
      .where(gte(recipes.createdAt, since))
      .groupBy(sql`to_char(${recipes.createdAt}, 'YYYY-MM-DD')`, recipes.aiGenerated),
    db.select({ tier: users.tier, n: sql<number>`count(*)::int` }).from(users).groupBy(users.tier),
    db.select({ visibility: recipes.visibility, n: sql<number>`count(*)::int` }).from(recipes).groupBy(recipes.visibility),
    db
      .select({ month: userUsage.month, n: sql<number>`coalesce(sum(${userUsage.aiCallsUsed}), 0)::int` })
      .from(userUsage)
      .groupBy(userUsage.month),
    db.select({ status: supportTickets.status, n: sql<number>`count(*)::int` }).from(supportTickets).groupBy(supportTickets.status),
    db
      .select({ featureKey: featureUpgradeClicks.featureKey, n: sql<number>`count(*)::int` })
      .from(featureUpgradeClicks)
      .where(gte(featureUpgradeClicks.createdAt, since))
      .groupBy(featureUpgradeClicks.featureKey),
  ]);

  for (const r of results) {
    if (r.status === "rejected") console.error("[admin/insights] query failed", r.reason);
  }

  const [signupRows, recipeRows, tierRows, visibilityRows, usageRows, ticketRows, upgradeClickRows] = results.map((r) =>
    r.status === "fulfilled" ? r.value : []
  ) as [
    { day: string; n: number }[],
    { day: string; aiGenerated: boolean; n: number }[],
    { tier: "free" | "pro" | "family"; n: number }[],
    { visibility: "private" | "unlisted" | "public" | "followers"; n: number }[],
    { month: string; n: number }[],
    { status: "open" | "triaged" | "closed"; n: number }[],
    { featureKey: string; n: number }[],
  ];

  const signupByDay = new Map(signupRows.map((r) => [r.day, r.n]));
  const signupSeries = lastNDays(DAYS).map((day) => ({ date: day, value: signupByDay.get(day) ?? 0 }));

  const recipesByDay = new Map<string, { manual: number; ai: number }>();
  for (const r of recipeRows) {
    const entry = recipesByDay.get(r.day) ?? { manual: 0, ai: 0 };
    if (r.aiGenerated) entry.ai += r.n; else entry.manual += r.n;
    recipesByDay.set(r.day, entry);
  }
  const recipesSeries = lastNDays(DAYS).map((day) => {
    const entry = recipesByDay.get(day) ?? { manual: 0, ai: 0 };
    return { label: formatShortDate(day), values: [entry.manual, entry.ai] };
  });

  const TIER_ORDER = ["free", "pro", "family"] as const;
  const tierByKey = new Map(tierRows.map((r) => [r.tier, r.n]));
  const tierData = TIER_ORDER.map((tier) => ({ label: tier, values: [tierByKey.get(tier) ?? 0] }));

  const VISIBILITY_ORDER = ["private", "unlisted", "followers", "public"] as const;
  const visByKey = new Map(visibilityRows.map((r) => [r.visibility, r.n]));
  const visibilityData = VISIBILITY_ORDER.map((v) => ({ label: v, values: [visByKey.get(v) ?? 0] }));

  const usageByMonth = new Map(usageRows.map((r) => [r.month, r.n]));
  const usageSeries = lastNMonths(6).map((month) => ({ date: month, value: usageByMonth.get(month) ?? 0 }));

  const STATUS_ORDER = ["open", "triaged", "closed"] as const;
  const statusByKey = new Map(ticketRows.map((r) => [r.status, r.n]));
  const statusData = STATUS_ORDER.map((s) => ({ label: s, values: [statusByKey.get(s) ?? 0] }));

  const FEATURE_LABEL = new Map<string, string>(FEATURE_DEFINITIONS.map((f) => [f.key, f.label]));
  const upgradeClickData = [...upgradeClickRows]
    .sort((a, b) => b.n - a.n)
    .map((r) => ({ label: FEATURE_LABEL.get(r.featureKey) ?? r.featureKey, values: [r.n] }));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Insights</h1>
        <p className="text-muted-foreground text-sm mt-1">Trends and breakdowns across the last {DAYS} days (or 6 months for usage).</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">New signups</CardTitle>
            <CardDescription>Daily, last {DAYS} days</CardDescription>
          </CardHeader>
          <CardContent>
            <TimeSeriesChart data={signupSeries} dateFormat="day" />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Recipes created</CardTitle>
            <CardDescription>Daily, manual vs AI-generated</CardDescription>
          </CardHeader>
          <CardContent>
            <BarChart data={recipesSeries} seriesLabels={["Manual", "AI-generated"]} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Users by tier</CardTitle>
            <CardDescription>All-time</CardDescription>
          </CardHeader>
          <CardContent>
            <BarChart data={tierData} seriesLabels={["Users"]} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Recipes by visibility</CardTitle>
            <CardDescription>All-time</CardDescription>
          </CardHeader>
          <CardContent>
            <BarChart data={visibilityData} seriesLabels={["Recipes"]} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">AI calls</CardTitle>
            <CardDescription>Monthly total across all users, last 6 months</CardDescription>
          </CardHeader>
          <CardContent>
            <TimeSeriesChart data={usageSeries} dateFormat="month" />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Support tickets by status</CardTitle>
            <CardDescription>All-time</CardDescription>
          </CardHeader>
          <CardContent>
            <BarChart data={statusData} seriesLabels={["Tickets"]} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Most-requested locked features</CardTitle>
            <CardDescription>&quot;See Pro plans&quot; clicks from a locked-feature upgrade prompt, last {DAYS} days</CardDescription>
          </CardHeader>
          <CardContent>
            {upgradeClickData.length > 0 ? (
              <BarChart data={upgradeClickData} seriesLabels={["Clicks"]} />
            ) : (
              <p className="text-sm text-muted-foreground">No upgrade-prompt clicks yet in this window.</p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
