import { prisma } from "@/lib/prisma";
import {
  getProposalPackage,
  TREASURY_USDC_ADDRESS,
  TREASURY_USDC_NETWORK,
  TREASURY_WALLET_LABEL,
} from "@/lib/a2a-growth";
import { CheckCircle2, Copy, Wallet } from "lucide-react";
import Link from "next/link";

export const dynamic = "force-dynamic";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

function getParam(params: Record<string, string | string[] | undefined>, key: string) {
  const value = params[key];
  return Array.isArray(value) ? value[0] || "" : value || "";
}

function formatUsdcAmount(feeCents: number) {
  return (feeCents / 100).toFixed(2);
}

export default async function ProposalSuccessPage({ searchParams }: { searchParams?: SearchParams }) {
  const params = searchParams ? await searchParams : {};
  const taskId = getParam(params, "task_id");
  const payment = getParam(params, "payment") || "stripe";
  const proposalPackage = getProposalPackage(getParam(params, "package"));
  const task = taskId
    ? await prisma.task.findUnique({
        where: { id: taskId },
        select: {
          id: true,
          title: true,
          status: true,
          reward_amount: true,
          reward_currency: true,
          referred_by_agent: true,
          stripe_payment_intent_id: true,
        },
      })
    : null;
  const stripeCaptured = payment === "stripe" && Boolean(task?.stripe_payment_intent_id);

  return (
    <main className="min-h-screen bg-zinc-950 px-5 py-10 text-zinc-100">
      <section className="mx-auto max-w-3xl">
        <Link href="/" className="text-sm font-medium text-zinc-400 hover:text-white">
          VibeWork AI 任務協作網路
        </Link>

        <div className="mt-8 rounded-lg border border-zinc-800 bg-zinc-900/80 p-6 shadow-2xl shadow-black/30">
          <div className="mb-5 flex items-center gap-3">
            <CheckCircle2 className="h-7 w-7 text-emerald-300" />
            <div>
              <p className="text-sm font-medium text-emerald-200">
                {payment === "wallet"
                  ? "待 USDC 轉帳確認"
                  : stripeCaptured
                    ? "提案付款已確認"
                    : "付款返回成功，等待 webhook 入帳確認"}
              </p>
              <h1 className="text-2xl font-semibold text-white">需求已進入 VibeWork private draft</h1>
            </div>
          </div>

          {task ? (
            <dl className="grid gap-4 rounded-md border border-zinc-800 bg-zinc-950 p-4 text-sm md:grid-cols-2">
              <div>
                <dt className="text-zinc-500">Proposal ID</dt>
                <dd className="mt-1 break-all text-zinc-100">{task.id}</dd>
              </div>
              <div>
                <dt className="text-zinc-500">Status</dt>
                <dd className="mt-1 text-zinc-100">{task.status}</dd>
              </div>
              <div>
                <dt className="text-zinc-500">Estimated bounty budget</dt>
                <dd className="mt-1 text-zinc-100">
                  ${(task.reward_amount / 100).toFixed(2)} {task.reward_currency}
                </dd>
              </div>
              <div>
                <dt className="text-zinc-500">Referral Agent</dt>
                <dd className="mt-1 break-all text-zinc-100">{task.referred_by_agent || "direct"}</dd>
              </div>
            </dl>
          ) : (
            <div className="rounded-md border border-amber-400/30 bg-amber-400/10 px-4 py-3 text-sm text-amber-100">
              找不到 proposal draft，請使用付款後返回的完整連結確認。
            </div>
          )}

          <div className="mt-5 rounded-md border border-sky-400/20 bg-sky-400/10 p-4">
            <p className="text-sm font-semibold text-sky-100">{proposalPackage.name}</p>
            <p className="mt-1 text-sm leading-6 text-sky-100/80">
              Routing fee: {proposalPackage.label}. 這筆費用是提案 intake、AI scoping 與 referral attribution，不等同最終 bounty payout。
            </p>
            <p className="mt-2 text-sm leading-6 text-sky-100/70">
              下一步：平台會整理需求、預算、驗收條件與可執行邊界；若適合執行，會再轉成 bounty、專案或顧問式交付。
            </p>
          </div>

          {payment === "wallet" ? (
            <div className="mt-5 rounded-md border border-emerald-400/20 bg-emerald-400/10 p-4">
              <div className="mb-3 flex items-center gap-2 text-sm font-semibold text-emerald-100">
                <Wallet className="h-4 w-4" />
                USDC wallet payment
              </div>
              <dl className="grid gap-3 text-sm">
                <div>
                  <dt className="text-emerald-100/70">Amount</dt>
                  <dd className="mt-1 text-emerald-50">{formatUsdcAmount(proposalPackage.feeCents)} USDC</dd>
                </div>
                <div>
                  <dt className="text-emerald-100/70">Network</dt>
                  <dd className="mt-1 text-emerald-50">{TREASURY_USDC_NETWORK || "Confirm network with VibeWork before transfer"}</dd>
                </div>
                <div>
                  <dt className="text-emerald-100/70">Wallet</dt>
                  <dd className="mt-1 break-all text-emerald-50">
                    {TREASURY_USDC_ADDRESS || `${TREASURY_WALLET_LABEL} is not configured yet`}
                  </dd>
                </div>
              </dl>
              {TREASURY_USDC_ADDRESS ? (
                <div className="mt-3 inline-flex items-center gap-2 rounded-md border border-emerald-300/30 px-3 py-2 text-xs leading-5 text-emerald-100">
                  <Copy className="h-3.5 w-3.5" />
                  轉帳備註請包含 Proposal ID；入帳確認前 referral ledger 不會進入可出金狀態。
                </div>
              ) : null}
            </div>
          ) : null}

          <div className="mt-6 flex flex-wrap gap-3">
            {task ? (
              <Link
                href={`/tasks/${task.id}`}
                className="inline-flex h-11 items-center justify-center rounded-md border border-zinc-700 px-4 text-sm font-medium text-zinc-100 hover:border-sky-400"
              >
                查看 draft
              </Link>
            ) : null}
            <Link
              href="/propose"
              className="inline-flex h-11 items-center justify-center rounded-md bg-sky-400 px-4 text-sm font-semibold text-zinc-950 hover:bg-sky-300"
            >
              新增另一個需求
            </Link>
          </div>
        </div>
      </section>
    </main>
  );
}
