import { useEffect, useState } from "react";
import type { RedemptionRuleInfo } from "@stamp/shared";

type RedeemModalProps = {
  rules: RedemptionRuleInfo[];
  collectedCount: number;
  onRedeem: (ruleId: string) => Promise<void>;
  onClose: () => void;
};

const CONFIRM_COUNTDOWN = 5;

export default function RedeemModal({ rules, collectedCount, onRedeem, onClose }: RedeemModalProps) {
  const [redeeming, setRedeeming] = useState<string | null>(null);
  const [error, setError] = useState("");
  const [confirmRuleId, setConfirmRuleId] = useState<string | null>(null);
  const [countdown, setCountdown] = useState(CONFIRM_COUNTDOWN);

  const confirmRule = confirmRuleId ? rules.find((r) => r.id === confirmRuleId) : null;

  // 5-second countdown that restarts each time the confirm panel opens
  useEffect(() => {
    if (!confirmRuleId) return;
    setCountdown(CONFIRM_COUNTDOWN);
    const interval = setInterval(() => {
      setCountdown((c) => {
        if (c <= 1) {
          clearInterval(interval);
          return 0;
        }
        return c - 1;
      });
    }, 1000);
    return () => clearInterval(interval);
  }, [confirmRuleId]);

  const openConfirm = (ruleId: string) => {
    setError("");
    setConfirmRuleId(ruleId);
  };

  const cancelConfirm = () => {
    if (redeeming) return;
    setConfirmRuleId(null);
  };

  const doRedeem = async () => {
    if (!confirmRule || countdown > 0) return;
    setRedeeming(confirmRule.id);
    setError("");
    try {
      await onRedeem(confirmRule.id);
      onClose();
    } catch (e) {
      setError(e instanceof Error ? e.message : "兑换失败");
      setConfirmRuleId(null);
    } finally {
      setRedeeming(null);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center animate-overlay-fade"
      style={{ backgroundColor: "var(--overlay)" }}
      onClick={(e) => {
        if (e.target !== e.currentTarget) return;
        if (confirmRuleId) return; // Don't dismiss during confirm flow
        onClose();
      }}
    >
      <div className="w-full max-w-lg bg-[var(--bg-cream)] rounded-t-2xl p-6 pb-10 animate-slide-up safe-bottom relative overflow-hidden">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">兑换奖品</h3>
          <button onClick={onClose} className="text-[var(--text-muted)] p-1">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <p className="text-sm text-[var(--text-secondary)] mb-4">
          当前已收集 <span className="font-semibold text-[var(--jade)]">{collectedCount}</span> 枚图章
        </p>

        {error && (
          <p className="text-sm text-[var(--terracotta)] mb-3">{error}</p>
        )}

        <div className="space-y-3">
          {rules.map((rule) => {
            const canRedeem = collectedCount >= rule.threshold;
            return (
              <div
                key={rule.id}
                className="flex items-center justify-between p-4 rounded-xl border"
                style={{
                  borderColor: canRedeem ? "var(--jade)" : "var(--border-muted)",
                  backgroundColor: canRedeem ? "rgba(45, 106, 79, 0.05)" : "white",
                }}
              >
                <div className="flex-1 min-w-0 mr-3">
                  <p className="text-sm font-medium text-[var(--text-primary)] truncate">
                    {rule.name}
                  </p>
                  {rule.description && (
                    <p className="text-xs text-[var(--text-muted)] mt-0.5 truncate">{rule.description}</p>
                  )}
                  <p className="text-xs text-[var(--text-muted)] mt-1">
                    需要 {rule.threshold} 枚图章
                  </p>
                </div>
                <button
                  onClick={() => openConfirm(rule.id)}
                  disabled={!canRedeem || !!redeeming}
                  className="shrink-0 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
                  style={{
                    backgroundColor: canRedeem ? "var(--jade)" : "var(--border-muted)",
                    color: canRedeem ? "white" : "var(--text-muted)",
                  }}
                >
                  兑换
                </button>
              </div>
            );
          })}
        </div>

      </div>

      {/* Confirmation dialog — centered over the sheet, highest priority */}
      {confirmRule && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center px-5 py-6 animate-overlay-fade"
          style={{ backgroundColor: "rgba(26, 26, 46, 0.6)" }}
          onClick={(e) => e.target === e.currentTarget && cancelConfirm()}
        >
          <div
            className="w-full max-w-sm bg-[var(--bg-cream)] rounded-2xl animate-scale-in overflow-hidden"
            style={{ boxShadow: "0 24px 60px rgba(26,26,46,0.35)" }}
          >
            {/* Warning at the top — most prominent, filled terracotta */}
            <div
              className="px-5 py-4"
              style={{
                backgroundColor: "var(--terracotta)",
                color: "#fff",
              }}
            >
              <div className="flex gap-3">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"
                  className="shrink-0 mt-0.5">
                  <path d="M12 9v4M12 17h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
                </svg>
                <div className="flex-1">
                  <p className="text-[11px] tracking-[0.25em] uppercase opacity-80 mb-0.5">Important</p>
                  <p className="text-[15px] font-semibold leading-snug">
                    请在工作人员的注视下进行兑换，并确保您已领取奖品
                  </p>
                </div>
              </div>
            </div>

            {/* Body */}
            <div className="px-5 pt-5 pb-5">
              <h3 className="text-base font-semibold text-[var(--text-primary)] mb-4">确认兑换</h3>

              {/* Reward */}
              <div className="rounded-xl border border-[var(--jade)] bg-[rgba(45,106,79,0.05)] p-3.5 mb-3">
                <p className="text-[10px] tracking-[0.2em] text-[var(--jade)] uppercase mb-1">Reward</p>
                <p className="text-sm font-semibold text-[var(--text-primary)]">{confirmRule.name}</p>
                {confirmRule.description && (
                  <p className="text-xs text-[var(--text-muted)] mt-0.5">{confirmRule.description}</p>
                )}
              </div>

              {/* Deduction summary */}
              <div className="rounded-xl border border-[var(--border-default)] bg-white p-3.5 mb-2">
                <div className="flex items-baseline justify-between">
                  <span className="text-xs text-[var(--text-muted)]">将扣除</span>
                  <span className="text-xl font-semibold text-[var(--terracotta)]">{confirmRule.threshold}</span>
                </div>
                <p className="text-xs text-[var(--text-muted)] mt-1 leading-relaxed">
                  按收集顺序扣除最早的 {confirmRule.threshold} 枚，剩余{" "}
                  <span className="font-medium text-[var(--text-secondary)]">
                    {collectedCount - confirmRule.threshold}
                  </span>{" "}
                  枚将继续保留。
                </p>
              </div>

              <p className="text-[11px] text-[var(--text-muted)] text-center mb-4">
                一旦确认，图章将立即扣除，此操作不可撤销
              </p>

              {/* Buttons */}
              <div className="flex gap-2.5">
                <button
                  onClick={cancelConfirm}
                  disabled={!!redeeming}
                  className="flex-1 py-3 rounded-xl text-sm font-medium border border-[var(--border-default)] text-[var(--text-secondary)] bg-white disabled:opacity-40"
                >
                  取消
                </button>
                <button
                  onClick={doRedeem}
                  disabled={countdown > 0 || !!redeeming}
                  className="flex-[1.3] py-3 rounded-xl text-sm font-medium transition-colors"
                  style={{
                    backgroundColor: countdown > 0 || redeeming ? "var(--border-default)" : "var(--jade)",
                    color: countdown > 0 || redeeming ? "var(--text-muted)" : "white",
                    boxShadow: countdown > 0 || redeeming ? "none" : "0 2px 8px rgba(45,106,79,0.25)",
                  }}
                >
                  {redeeming
                    ? "兑换中..."
                    : countdown > 0
                      ? `请阅读提示 ${countdown}s`
                      : "确认兑换"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
