import { db } from "@/lib/db";
import { tips } from "@/lib/db/schema";
import { desc, eq } from "drizzle-orm";
import TipsPageClient from "@/components/TipsPageClient";
import { confirmCheckoutSession } from "@/lib/confirmPayment";
import { getSetting } from "@/lib/settings";

export const dynamic = "force-dynamic";

export default async function TipsPage({
  searchParams,
}: {
  searchParams: Promise<{ session_id?: string; acct?: string }>;
}) {
  const { session_id, acct } = await searchParams;
  let justConfirmed = false;
  if (session_id) {
    const result = await confirmCheckoutSession(session_id, acct);
    justConfirmed = !!result;
  }

  const rows = await db
    .select()
    .from(tips)
    .where(eq(tips.isPublic, true))
    .orderBy(desc(tips.createdAt));

  const supporters = rows.slice(0, 50).map((r) => ({
    name: r.name,
    amount: r.amount,
    isRecurring: r.isRecurring,
    createdAt: r.createdAt ? r.createdAt.toString() : new Date().toString(),
  }));

  const otherLabel = await getSetting("tipOtherLabel", "Other");
  const presetAmountsRaw = await getSetting("tipPresetAmounts", JSON.stringify([{ amount: 5 }, { amount: 10 }, { amount: 25 }, { amount: 50 }, { amount: 100 }, { amount: 200 }]));
  const vipPresetAmountsRaw = await getSetting("tipVipPresetAmounts", JSON.stringify([{ amount: 500 }, { amount: 1000 }, { amount: 2500 }]));
  const vipBoxTitle = await getSetting("tipVipBoxTitle", "Special VIP Donators");
  const humbleTitle = await getSetting("tipHumbleTitle", "I can't give much, but I'll do my best to help.");
  const humbleAmount = parseFloat(await getSetting("tipHumbleAmount", "2")) || 2;
  const humbleEnabled = (await getSetting("tipHumbleEnabled", "true")) === "true";
  const normalClickSound = await getSetting("tipNormalClickSound", "");
  const vipClickSound = await getSetting("tipVipClickSound", "");
  const normalPopupGif = await getSetting("tipNormalPopupGif", "");
  const vipPopupGif = await getSetting("tipVipPopupGif", "");
  const popupDurationSeconds = parseFloat(await getSetting("tipPopupDurationSeconds", "2")) || 2;
  const normalGifLength = await getSetting("tipNormalGifLength", "");
  const vipGifLength = await getSetting("tipVipGifLength", "");
  const successGif = await getSetting("tipSuccessGif", "");
  const successGifLength = await getSetting("tipSuccessGifLength", "");
  const successSound = await getSetting("tipSuccessSound", "");
  const successDurationSeconds = parseFloat(await getSetting("tipSuccessDurationSeconds", "3")) || 3;

  // Old installs may still have plain number arrays like [5, 10, 25] saved —
  // normalize those into the newer {amount, emoji} shape transparently.
  function normalizeButtons(raw: string, fallback: { amount: number; emoji?: string }[]) {
    try {
      const parsed = JSON.parse(raw);
      if (!Array.isArray(parsed) || parsed.length === 0) return fallback;
      return parsed.map((b: any) => (typeof b === "number" ? { amount: b, emoji: "" } : { amount: b.amount, emoji: b.emoji || "" }));
    } catch {
      return fallback;
    }
  }
  const presetAmounts = normalizeButtons(presetAmountsRaw, [{ amount: 5 }, { amount: 10 }, { amount: 25 }, { amount: 50 }, { amount: 100 }, { amount: 200 }]);
  const vipPresetAmounts = normalizeButtons(vipPresetAmountsRaw, [{ amount: 500 }, { amount: 1000 }, { amount: 2500 }]);

  return (
    <TipsPageClient
      supporters={supporters}
      justConfirmed={justConfirmed}
      otherLabel={otherLabel}
      presetAmounts={presetAmounts}
      vipPresetAmounts={vipPresetAmounts}
      vipBoxTitle={vipBoxTitle}
      humbleEnabled={humbleEnabled}
      humbleTitle={humbleTitle}
      humbleAmount={humbleAmount}
      normalClickSound={normalClickSound}
      vipClickSound={vipClickSound}
      normalPopupGif={normalPopupGif}
      vipPopupGif={vipPopupGif}
      popupDurationSeconds={popupDurationSeconds}
      normalGifLength={normalGifLength}
      vipGifLength={vipGifLength}
      successGif={successGif}
      successGifLength={successGifLength}
      successSound={successSound}
      successDurationSeconds={successDurationSeconds}
    />
  );
}
