import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import type { StampWithStatus, RedemptionRuleInfo, RedemptionRecord } from "@stamp/shared";
import { apiFetch } from "../lib/api";
import { useAuth } from "../lib/auth";
import StampGrid from "../components/StampGrid";
import RedeemModal from "../components/RedeemModal";
import RegisterModal from "../components/RegisterModal";

export default function AlbumPage() {
  const navigate = useNavigate();
  const { user, isLoading: authLoading } = useAuth();
  const [stamps, setStamps] = useState<StampWithStatus[]>([]);
  const [rules, setRules] = useState<RedemptionRuleInfo[]>([]);
  const [history, setHistory] = useState<RedemptionRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [showRedeem, setShowRedeem] = useState(false);
  const [showRegister, setShowRegister] = useState(false);

  const collectedCount = stamps.filter((s) => s.collected).length;

  const fetchData = async () => {
    setLoading(true);
    try {
      const [stampsData, rulesData] = await Promise.all([
        apiFetch<StampWithStatus[]>("/stamps"),
        apiFetch<RedemptionRuleInfo[]>("/redemption/rules"),
      ]);
      setStamps(stampsData);
      setRules(rulesData);

      if (user) {
        const historyData = await apiFetch<RedemptionRecord[]>("/redemption/history");
        setHistory(historyData);
      }
    } catch {
      // Stamps endpoint works without auth
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!authLoading) fetchData();
  }, [authLoading, user]);

  const handleRedeem = async (ruleId: string) => {
    await apiFetch("/redemption/redeem", {
      method: "POST",
      body: JSON.stringify({ ruleId }),
    });
    await fetchData();
  };

  const handleRedeemClick = () => {
    if (!user) {
      setShowRegister(true);
      return;
    }
    setShowRedeem(true);
  };

  if (loading || authLoading) {
    return (
      <div className="min-h-screen bg-[var(--bg-cream)] flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-[var(--gold)] border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[var(--bg-cream)] paper-texture">
      {/* Header */}
      <div className="sticky top-0 z-40 bg-[var(--bg-cream)]/90 backdrop-blur-sm border-b border-[var(--border-muted)]">
        <div className="flex items-center justify-between px-4 py-3">
          <button onClick={() => navigate("/")} className="text-[var(--text-secondary)] p-1">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M15 18l-6-6 6-6" />
            </svg>
          </button>
          <h1 className="text-base font-semibold text-[var(--text-primary)]">图章集册</h1>
          <div className="w-8" />
        </div>
      </div>

      {/* Progress */}
      <div className="px-6 pt-5 pb-5">
        <div className="flex items-end justify-between mb-2">
          <div>
            <div className="text-xs text-[var(--text-muted)] mb-0.5">收集进度</div>
            <div className="flex items-baseline gap-1">
              <span className="text-2xl font-semibold text-[var(--text-primary)]">{collectedCount}</span>
              <span className="text-sm text-[var(--text-muted)]">/ {stamps.length}</span>
            </div>
          </div>
          {stamps.length > 0 && collectedCount < stamps.length && (
            <span className="text-xs text-[var(--text-secondary)] pb-1">
              还差 {stamps.length - collectedCount} 枚集齐
            </span>
          )}
          {stamps.length > 0 && collectedCount === stamps.length && (
            <span className="text-xs font-medium text-[var(--gold)] pb-1">已集齐全部图章 ✨</span>
          )}
        </div>
        <div className="h-1.5 bg-[var(--border-muted)] rounded-full overflow-hidden">
          <div
            className="h-full bg-gradient-to-r from-[var(--gold)] to-[var(--terracotta)] rounded-full transition-all duration-500"
            style={{ width: stamps.length ? `${(collectedCount / stamps.length) * 100}%` : "0%" }}
          />
        </div>
      </div>

      {/* Stamp Grid */}
      <div className="px-4 pb-6">
        <StampGrid stamps={stamps} />
      </div>

      {/* Redeem Section */}
      {rules.length > 0 && (() => {
        const availableCount = rules.filter((r) => collectedCount >= r.threshold).length;
        const canRedeem = availableCount > 0;
        return (
          <div className="px-6 pb-6">
            <button
              onClick={handleRedeemClick}
              disabled={!canRedeem}
              className="w-full py-3.5 rounded-xl text-sm font-medium transition-all disabled:cursor-not-allowed flex items-center justify-center gap-2"
              style={{
                backgroundColor: canRedeem ? "var(--jade)" : "var(--border-muted)",
                color: canRedeem ? "white" : "var(--text-muted)",
                boxShadow: canRedeem ? "0 2px 8px rgba(45,106,79,0.25)" : "none",
              }}
            >
              <span>{canRedeem ? "兑换奖品" : "继续收集以解锁奖品"}</span>
              {canRedeem && (
                <span className="text-xs px-2 py-0.5 rounded-full bg-white/20">
                  {availableCount} 个可兑换
                </span>
              )}
            </button>
          </div>
        );
      })()}

      {/* Redemption History */}
      {history.length > 0 && (
        <div className="px-6 pb-8">
          <h3 className="text-sm font-medium text-[var(--text-secondary)] mb-3">兑换记录</h3>
          <div className="space-y-2">
            {history.map((r) => (
              <div key={r.id} className="flex items-center justify-between py-2 px-3 bg-white/60 rounded-lg">
                <div>
                  <p className="text-sm text-[var(--text-primary)]">{r.ruleName}</p>
                  <p className="text-xs text-[var(--text-muted)]">
                    {new Date(r.redeemedAt).toLocaleDateString("zh-CN")}
                  </p>
                </div>
                <span className="text-xs text-[var(--jade)]">已兑换</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Modals */}
      {showRedeem && (
        <RedeemModal
          rules={rules}
          collectedCount={collectedCount}
          onRedeem={handleRedeem}
          onClose={() => setShowRedeem(false)}
        />
      )}

      {showRegister && (
        <RegisterModal
          onSuccess={() => {
            setShowRegister(false);
            fetchData();
          }}
          onClose={() => setShowRegister(false)}
        />
      )}
    </div>
  );
}
