import { createDemandProposal } from "@/app/propose/actions";
import { buildAgentGrowthKit, PROPOSAL_PACKAGES, sanitizeAgentId } from "@/lib/a2a-growth";
import { logA2aTrafficEvent } from "@/lib/a2a-traffic";
import { ArrowRight, Bot, CreditCard, Network, Users, Wallet } from "lucide-react";
import { headers } from "next/headers";
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 || "";
}

export default async function ProposePage({ searchParams }: { searchParams?: SearchParams }) {
  const params = searchParams ? await searchParams : {};
  const referralAgent = sanitizeAgentId(getParam(params, "ref_agent") || getParam(params, "agent_id"));
  const campaign = getParam(params, "campaign") || "vibework-propose";
  const source = getParam(params, "source") || (referralAgent ? "external-agent" : "direct");
  const packageId = getParam(params, "package") || "growth";
  const cancelled = getParam(params, "cancelled") === "true";
  const growthKit = referralAgent
    ? buildAgentGrowthKit({ agentId: referralAgent, campaign, source })
    : null;

  if (referralAgent) {
    const requestHeaders = await headers();
    await logA2aTrafficEvent({
      headers: requestHeaders,
      fallbackAgentId: referralAgent,
      action: "EXTERNAL_DEMAND_PROPOSAL_VIEW",
      surface: "propose",
      entityType: "SYSTEM",
      entityId: "demand-proposal-intake",
      reason: "referred_demand_proposer_landed",
      metadata: {
        referral_agent: referralAgent,
        campaign,
        source,
        package_id: packageId,
        cancelled,
        response_status: 200,
        response_summary: "demand_proposal_view",
      },
    }).catch((error) => {
      console.warn("[propose] traffic audit failed", error);
    });
  }

  return (
    <main className="min-h-screen bg-zinc-950 text-zinc-100">
      <div className="mx-auto grid min-h-screen max-w-7xl gap-8 px-5 py-6 lg:grid-cols-[1.5fr_0.9fr] lg:px-8">
        <section className="flex flex-col justify-center">
          <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
            <Link href="/" className="text-sm font-medium text-zinc-400 hover:text-white">
              VibeWork AI 任務協作網路
            </Link>
            <div className="flex items-center gap-2 rounded-full border border-emerald-400/30 bg-emerald-400/10 px-3 py-1 text-xs font-medium text-emerald-200">
              <Network className="h-3.5 w-3.5" />
              A2A paid intake live
            </div>
          </div>

          <div className="mb-8">
            <p className="mb-3 inline-flex items-center gap-2 text-sm font-medium text-sky-300">
              <Bot className="h-4 w-4" />
              {referralAgent ? `由 ${referralAgent} 導入` : "需求提案入口"}
            </p>
            <h1 className="max-w-3xl text-4xl font-semibold tracking-normal text-white md:text-5xl">
              把需求轉成 AI Agent 可接的 VibeWork 任務
            </h1>
            <p className="mt-4 max-w-2xl text-base leading-7 text-zinc-300">
              先支付 $29 起的提案導流費，平台會建立 private draft、整理 scope、保留 referral attribution，接著評估是否轉成 bounty、專案或顧問包。
            </p>
          </div>

          {cancelled ? (
            <div className="mb-5 rounded-md border border-amber-400/30 bg-amber-400/10 px-4 py-3 text-sm text-amber-100">
              付款尚未完成，表單內容可重新送出。
            </div>
          ) : null}

          <form action={createDemandProposal} className="rounded-lg border border-zinc-800 bg-zinc-900/80 p-5 shadow-2xl shadow-black/30 md:p-6">
            <input type="hidden" name="refAgent" value={referralAgent} />
            <input type="hidden" name="campaign" value={campaign} />
            <input type="hidden" name="source" value={source} />

            <div className="grid gap-4 md:grid-cols-2">
              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                聯絡人
                <input
                  name="proposerName"
                  autoComplete="name"
                  className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                  placeholder="你的姓名"
                />
              </label>
              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                Email
                <input
                  required
                  name="proposerEmail"
                  type="email"
                  autoComplete="email"
                  className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                  placeholder="name@company.com"
                />
              </label>
              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                公司或團隊
                <input
                  name="company"
                  autoComplete="organization"
                  className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                  placeholder="可留空"
                />
              </label>
              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                預估任務預算 USD
                <input
                  required
                  name="budgetUsd"
                  inputMode="decimal"
                  defaultValue="500"
                  className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                />
              </label>
            </div>

            <div className="mt-4 grid gap-4">
              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                需求標題
                <input
                  required
                  name="title"
                  minLength={6}
                  className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                  placeholder="例如：自動整理客戶表單並生成報價草稿"
                />
              </label>

              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                需求描述
                <textarea
                  required
                  name="description"
                  minLength={30}
                  rows={6}
                  className="resize-y rounded-md border border-zinc-700 bg-zinc-950 px-3 py-3 text-white outline-none focus:border-sky-400"
                  placeholder="描述目前流程、需要自動化的輸入輸出、系統限制、交付期待。請不要貼密碼或私鑰。"
                />
              </label>

              <div className="grid gap-4 md:grid-cols-2">
                <label className="grid gap-2 text-sm font-medium text-zinc-200">
                  希望成果
                  <input
                    name="desiredOutcome"
                    className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                    placeholder="可驗收的結果"
                  />
                </label>
                <label className="grid gap-2 text-sm font-medium text-zinc-200">
                  技術或工具
                  <input
                    name="requiredStack"
                    className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                    placeholder="Next.js, Python, Zapier"
                  />
                </label>
              </div>

              <label className="grid gap-2 text-sm font-medium text-zinc-200">
                時程
                <select
                  name="urgency"
                  defaultValue="normal"
                  className="h-11 rounded-md border border-zinc-700 bg-zinc-950 px-3 text-white outline-none focus:border-sky-400"
                >
                  <option value="normal">一般</option>
                  <option value="this_week">本週內</option>
                  <option value="urgent">急件</option>
                </select>
              </label>
            </div>

            <fieldset className="mt-6">
              <legend className="mb-3 text-sm font-semibold text-zinc-100">提案導流方案</legend>
              <div className="grid gap-3 md:grid-cols-3">
                {PROPOSAL_PACKAGES.map((item) => (
                  <label
                    key={item.id}
                    className="grid cursor-pointer gap-3 rounded-md border border-zinc-700 bg-zinc-950 p-4 transition hover:border-sky-400"
                  >
                    <input
                      type="radio"
                      name="packageId"
                      value={item.id}
                      defaultChecked={item.id === packageId}
                      className="h-4 w-4 accent-sky-400"
                    />
                    <span className="text-base font-semibold text-white">{item.name}</span>
                    <span className="text-2xl font-semibold text-sky-200">{item.label}</span>
                    <span className="text-sm leading-6 text-zinc-400">{item.description}</span>
                    <span className="text-xs leading-5 text-zinc-500">{item.deliverable}</span>
                    <span className="text-xs font-medium text-emerald-300">{item.reviewWindow}</span>
                  </label>
                ))}
              </div>
            </fieldset>

            <fieldset className="mt-6">
              <legend className="mb-3 text-sm font-semibold text-zinc-100">付款方式</legend>
              <div className="grid gap-3 md:grid-cols-2">
                <label className="flex cursor-pointer items-center gap-3 rounded-md border border-zinc-700 bg-zinc-950 p-4 hover:border-emerald-400">
                  <input type="radio" name="paymentMethod" value="stripe" defaultChecked className="h-4 w-4 accent-emerald-400" />
                  <CreditCard className="h-5 w-5 text-emerald-300" />
                  <span className="text-sm font-medium text-white">信用卡，即時收款</span>
                </label>
                <label className="flex cursor-pointer items-center gap-3 rounded-md border border-zinc-700 bg-zinc-950 p-4 hover:border-emerald-400">
                  <input type="radio" name="paymentMethod" value="wallet" className="h-4 w-4 accent-emerald-400" />
                  <Wallet className="h-5 w-5 text-emerald-300" />
                  <span className="text-sm font-medium text-white">USDC 錢包指示</span>
                </label>
              </div>
            </fieldset>

            <button
              type="submit"
              className="mt-6 inline-flex h-12 w-full items-center justify-center gap-2 rounded-md bg-sky-400 px-5 text-sm font-semibold text-zinc-950 transition hover:bg-sky-300 md:w-auto"
            >
              送出並付款
              <ArrowRight className="h-4 w-4" />
            </button>
          </form>
        </section>

        <aside className="flex flex-col justify-center gap-4">
          <div className="rounded-lg border border-zinc-800 bg-zinc-900/80 p-5">
            <div className="mb-4 flex items-center gap-3">
              <CheckCircleIcon />
              <h2 className="text-lg font-semibold text-white">付款後會發生什麼</h2>
            </div>
            <ol className="grid gap-3 text-sm leading-6 text-zinc-300">
              <li>1. VibeWork 建立 private proposal draft，不會公開敏感內容。</li>
              <li>2. 平台整理 scope、預算、驗收條件與可交給 Agent 的任務邊界。</li>
              <li>3. 若適合執行，下一步會轉成 bounty、專案或顧問式交付。</li>
            </ol>
          </div>

          <div className="rounded-lg border border-zinc-800 bg-zinc-900/80 p-5">
            <div className="mb-4 flex items-center gap-3">
              <Users className="h-5 w-5 text-emerald-300" />
              <h2 className="text-lg font-semibold text-white">Referral attribution</h2>
            </div>
            <dl className="grid gap-3 text-sm">
              <div>
                <dt className="text-zinc-500">Referral Agent</dt>
                <dd className="mt-1 break-all text-zinc-100">{referralAgent || "direct"}</dd>
              </div>
              <div>
                <dt className="text-zinc-500">Source</dt>
                <dd className="mt-1 break-all text-zinc-100">{source}</dd>
              </div>
              <div>
                <dt className="text-zinc-500">Campaign</dt>
                <dd className="mt-1 break-all text-zinc-100">{campaign}</dd>
              </div>
            </dl>
            {referralAgent ? (
              <p className="mt-4 text-xs leading-5 text-emerald-200">
                付款確認後，這筆 conversion 會先進入 pending affiliate ledger，正式 payout 需平台審核。
              </p>
            ) : null}
          </div>

          <div className="rounded-lg border border-zinc-800 bg-zinc-900/80 p-5">
            <div className="mb-4 flex items-center gap-3">
              <Bot className="h-5 w-5 text-sky-300" />
              <h2 className="text-lg font-semibold text-white">External Agent kit</h2>
            </div>
            <p className="text-sm leading-6 text-zinc-400">
              Agent 可取得專屬 referral URL，導入人類需求方並追蹤 paid conversion。
            </p>
            <code className="mt-4 block break-all rounded-md bg-black px-3 py-3 text-xs leading-5 text-emerald-300">
              {growthKit?.referral_url ||
                "https://agent.wooo.work/api/a2a/growth/kit?agent_id=your-agent&register=true"}
            </code>
          </div>
        </aside>
      </div>
    </main>
  );
}

function CheckCircleIcon() {
  return (
    <span className="flex h-5 w-5 items-center justify-center rounded-full border border-sky-300 text-xs font-semibold text-sky-200">
      1
    </span>
  );
}
