import { useState, useEffect, useCallback } from "react";
import type { ReactNode } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import type { PrizeInfo } from "@stamp/shared";
import { apiFetch } from "../lib/api";
import { useAuth } from "../lib/auth";
import FloatingButton from "../components/FloatingButton";
import StampPopup from "../components/StampPopup";
import RegisterModal from "../components/RegisterModal";

const PENDING_STAMP_KEY = "stamp_pending_collect";

type StampDetail = {
  id: string;
  name: string;
  note: string | null;
  imageColor: string;
  imageGrey: string;
  prize: PrizeInfo | null;
};

type CollectState = "idle" | "loading" | "show_stamp" | "needs_register" | "collecting" | "collected" | "already_collected";

const RULES: { num: string; title: string; desc: ReactNode }[] = [
  {
    num: "01",
    title: "去朝天宫读城",
    desc: "活动期间，用户可在朝天宫街道辖区范围内自由探索，拍摄美食美景，记录你眼中的城南烟火气——红墙下的光影、打钉巷里热腾腾的锅贴、南台巷排队的咖啡店，街角一只晒太阳的猫……",
  },
  {
    num: "02",
    title: "线上打卡",
    desc: (
      <>
        将您的美图在小红书或者微博带下列两个话题{" "}
        <span className="text-[var(--terracotta)] font-medium">#我在朝天宫读城</span>
        {" "}
        <span className="text-[var(--terracotta)] font-medium">#跟着巷主去读城</span>
        {" "}发布笔记或微博即可完成线上打卡，发布时别忘了附带定位信息。
      </>
    ),
  },
  {
    num: "03",
    title: "线下打卡",
    desc: '前往任意一家门口贴有"读城窗口"标志的小店，进店后找到活动立牌，触碰 NFC 热点，在对应网页中完成线下打卡。',
  },
  {
    num: "04",
    title: "解锁权益",
    desc: "用户完成线上打卡、线下打卡后，即可在小店解锁活动权益。活动期间每个账号在同一小店仅享受 1 次权益，权益现场核销，不重复享受，名额有限，先到先得。",
  },
  {
    num: "05",
    title: "活动时间",
    desc: (
      <span className="text-[var(--terracotta)] font-medium">
        2026 年 4 月 21 日 — 2026 年 5 月 21 日
      </span>
    ),
  },
];

export default function LandingPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { user, isLoading: authLoading } = useAuth();

  const stampId = searchParams.get("stamp");

  const [stamp, setStamp] = useState<StampDetail | null>(null);
  const [collectState, setCollectState] = useState<CollectState>("idle");

  // Fetch stamp info when stampId is present
  useEffect(() => {
    if (!stampId || authLoading) return;
    setCollectState("loading");
    apiFetch<StampDetail>(`/stamps/${stampId}`)
      .then((data) => {
        setStamp(data);
        setCollectState("show_stamp");
      })
      .catch(() => {
        setCollectState("idle");
      });
  }, [stampId, authLoading]);

  const doCollect = useCallback(async () => {
    if (!stampId) return;
    setCollectState("collecting");
    try {
      await apiFetch(`/stamps/${stampId}/collect`, { method: "POST" });
      setCollectState("collected");
      sessionStorage.removeItem(PENDING_STAMP_KEY);
    } catch (e) {
      const msg = e instanceof Error ? e.message : "";
      if (msg.includes("已经收集")) {
        setCollectState("already_collected");
      } else {
        setCollectState("idle");
      }
    }
  }, [stampId]);

  // Auto-collect if user just registered and has a pending stamp
  useEffect(() => {
    if (authLoading || !user || collectState !== "show_stamp" || !stampId) return;
    const pending = sessionStorage.getItem(PENDING_STAMP_KEY);
    if (pending === stampId) {
      doCollect();
    }
  }, [authLoading, user, collectState, stampId, doCollect]);

  const handleCollect = () => {
    if (!user) {
      sessionStorage.setItem(PENDING_STAMP_KEY, stampId!);
      setCollectState("needs_register");
      return;
    }
    doCollect();
  };

  const handleRegisterSuccess = () => {
    setCollectState("show_stamp");
    doCollect();
  };

  const handleClose = () => {
    setCollectState("idle");
    setStamp(null);
    navigate("/", { replace: true });
  };

  const showStampPopup = stamp && (collectState === "show_stamp" || collectState === "collecting");
  const showCollectedPopup = stamp && collectState === "collected";
  const showAlreadyPopup = stamp && collectState === "already_collected";
  const showRegister = collectState === "needs_register";

  return (
    <div className="min-h-svh bg-[var(--bg-cream)]">
      {/* ═══════════ POSTER ═══════════ */}
      <section className="relative w-full">
        <img
          src="/poster.jpg"
          alt="读城·行走朝天宫"
          className="block w-full h-auto select-none"
          draggable={false}
        />
      </section>

      {/* ═══════════ RULES ═══════════ */}
      <section className="relative paper-texture px-6 py-14 pb-32">
        <div className="relative z-10 max-w-sm mx-auto">
          <div className="flex items-center gap-3 mb-3">
            <span className="block w-6 h-px bg-[var(--text-primary)]/20" />
            <span className="text-[var(--text-muted)] text-[10px] tracking-[0.3em] uppercase">
              Rules
            </span>
          </div>
          <h2
            className="text-[var(--text-primary)] text-2xl leading-snug mb-10"
            style={{ fontFamily: "'Playfair Display', serif" }}
          >
            活动规则
          </h2>

          <ol className="space-y-0 stagger-children">
            {RULES.map((rule, i) => (
              <li key={rule.num} className="relative flex gap-5">
                <div className="flex flex-col items-center shrink-0">
                  <div
                    className="w-11 h-11 rounded-full border-2 flex items-center justify-center"
                    style={{
                      borderColor: "var(--gold)",
                      background: "rgba(212, 165, 116, 0.06)",
                    }}
                  >
                    <span
                      className="text-[var(--gold)] text-xs"
                      style={{ fontFamily: "'Playfair Display', serif", fontWeight: 600 }}
                    >
                      {rule.num}
                    </span>
                  </div>
                  {i < RULES.length - 1 && (
                    <div className="w-px flex-1 min-h-[40px] bg-[var(--gold)]/20" />
                  )}
                </div>
                <div className="pb-8 pt-1.5">
                  <h3 className="text-base font-semibold text-[var(--text-primary)] mb-1.5">
                    {rule.title}
                  </h3>
                  <p className="text-sm text-[var(--text-secondary)] leading-[1.9]">
                    {rule.desc}
                  </p>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      <FloatingButton />

      {/* ═══════════ Collection Overlays ═══════════ */}
      {showStampPopup && (
        <StampPopup
          name={stamp.name}
          imageColor={stamp.imageColor}
          note={stamp.note}
          prize={stamp.prize}
          status="preview"
          onCollect={handleCollect}
          onClose={handleClose}
        />
      )}
      {showCollectedPopup && (
        <StampPopup
          name={stamp.name}
          imageColor={stamp.imageColor}
          note={stamp.note}
          prize={stamp.prize}
          status="collected"
          onClose={handleClose}
        />
      )}
      {showAlreadyPopup && (
        <StampPopup
          name={stamp.name}
          imageColor={stamp.imageColor}
          note={stamp.note}
          prize={stamp.prize}
          status="already"
          onClose={handleClose}
        />
      )}
      {showRegister && (
        <RegisterModal
          onSuccess={handleRegisterSuccess}
          onClose={() => setCollectState("show_stamp")}
        />
      )}
    </div>
  );
}
