"use client";
import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { SparkleBurst, GifPopup, cappedDuration } from "@/components/Celebration";

type ButtonDef = { amount: number; emoji?: string };
type Selection = { source: "normal" | "vip" | "humble" | "custom"; amount: number } | null;

export default function TipsPage({
  supporters,
  justConfirmed = false,
  otherLabel = "Other",
  presetAmounts = [{ amount: 5 }, { amount: 10 }, { amount: 25 }, { amount: 50 }, { amount: 100 }, { amount: 200 }],
  vipPresetAmounts = [{ amount: 500 }, { amount: 1000 }, { amount: 2500 }],
  vipBoxTitle = "Special VIP Donators",
  humbleEnabled = true,
  humbleTitle = "I can't give much, but I'll do my best to help.",
  humbleAmount = 2,
  normalClickSound = "",
  vipClickSound = "",
  normalPopupGif = "",
  vipPopupGif = "",
  popupDurationSeconds = 2,
  normalGifLength = "",
  vipGifLength = "",
  successGif = "",
  successGifLength = "",
  successSound = "",
  successDurationSeconds = 3,
}: {
  supporters: { name: string; amount: number; isRecurring: boolean; createdAt: string }[];
  justConfirmed?: boolean;
  otherLabel?: string;
  presetAmounts?: ButtonDef[];
  vipPresetAmounts?: ButtonDef[];
  vipBoxTitle?: string;
  humbleEnabled?: boolean;
  humbleTitle?: string;
  humbleAmount?: number;
  normalClickSound?: string;
  vipClickSound?: string;
  normalPopupGif?: string;
  vipPopupGif?: string;
  popupDurationSeconds?: number;
  normalGifLength?: string;
  vipGifLength?: string;
  successGif?: string;
  successGifLength?: string;
  successSound?: string;
  successDurationSeconds?: number;
}) {
  const [selection, setSelection] = useState<Selection>({ source: "normal", amount: presetAmounts[0]?.amount || 25 });
  const [customAmount, setCustomAmount] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");
  const [email, setEmail] = useState("");
  const [isPrivate, setIsPrivate] = useState(false);
  const [isRecurring, setIsRecurring] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [popup, setPopup] = useState<"normal" | "vip" | null>(null);
  const [showSuccessCelebration, setShowSuccessCelebration] = useState(false);
  const router = useRouter();
  const { data: session } = useSession();
  const loggedIn = !!session?.user;

  const normalAudioRef = useRef<HTMLAudioElement | null>(null);
  const vipAudioRef = useRef<HTMLAudioElement | null>(null);
  const successAudioRef = useRef<HTMLAudioElement | null>(null);

  // On successful payment return, celebrate — duration auto-capped to the
  // GIF's real length if one was set, so it's never held open too long.
  useEffect(() => {
    if (justConfirmed) {
      setShowSuccessCelebration(true);
      if (successSound && successAudioRef.current) {
        successAudioRef.current.currentTime = 0;
        successAudioRef.current.play().catch(() => {});
      }
      const duration = cappedDuration(successDurationSeconds, successGifLength);
      const t = setTimeout(() => setShowSuccessCelebration(false), duration * 1000);
      return () => clearTimeout(t);
    }
  }, [justConfirmed]);

  const finalAmount = selection?.source === "custom" ? parseFloat(customAmount) || 0 : selection?.amount || 0;

  function triggerPopup(kind: "normal" | "vip", gifLength: string) {
    setPopup(kind);
    const duration = cappedDuration(popupDurationSeconds, gifLength);
    setTimeout(() => setPopup(null), duration * 1000);
  }

  function pickNormal(p: number) {
    setSelection({ source: "normal", amount: p });
    if (normalClickSound && normalAudioRef.current) {
      normalAudioRef.current.currentTime = 0;
      normalAudioRef.current.play().catch(() => {});
    }
    triggerPopup("normal", normalGifLength);
  }

  function pickCustom() {
    setSelection({ source: "custom", amount: 0 });
  }

  function pickVip(p: number) {
    setSelection({ source: "vip", amount: p });
    if (vipClickSound && vipAudioRef.current) {
      vipAudioRef.current.currentTime = 0;
      vipAudioRef.current.play().catch(() => {});
    }
    triggerPopup("vip", vipGifLength);
  }

  function pickHumble() {
    setSelection({ source: "humble", amount: humbleAmount });
    if (normalClickSound && normalAudioRef.current) {
      normalAudioRef.current.currentTime = 0;
      normalAudioRef.current.play().catch(() => {});
    }
    triggerPopup("normal", normalGifLength);
  }

  async function handleSubmit() {
    setError("");
    if (!name.trim()) {
      setError("Please tell us how to thank you.");
      return;
    }
    if (!finalAmount || finalAmount <= 0) {
      setError("Enter a valid amount.");
      return;
    }
    setLoading(true);
    const params = new URLSearchParams({
      type: "tip",
      amount: String(finalAmount),
      description: "Support the Creators",
      name,
      message,
      isRecurring: isRecurring ? "1" : "0",
      isPublic: isPrivate ? "0" : "1",
    });
    if (email.trim()) params.set("email", email.trim());
    router.push(`/checkout?${params.toString()}`);
  }

  const showNormalGif = popup === "normal" && !!normalPopupGif;
  const showNormalSparkle = popup === "normal" && !normalPopupGif;
  const showVipGif = popup === "vip" && !!vipPopupGif;
  const showVipSparkle = popup === "vip" && !vipPopupGif;

  return (
    <div className="max-w-2xl mx-auto">
      <GifPopup src={normalPopupGif} show={showNormalGif} />
      <GifPopup src={vipPopupGif} show={showVipGif} />
      <SparkleBurst show={showNormalSparkle} />
      <SparkleBurst show={showVipSparkle} big />
      <GifPopup src={successGif} show={showSuccessCelebration && !!successGif} />
      <SparkleBurst show={showSuccessCelebration && !successGif} big />
      {normalClickSound && <audio ref={normalAudioRef} src={normalClickSound} preload="auto" />}
      {vipClickSound && <audio ref={vipAudioRef} src={vipClickSound} preload="auto" />}
      {successSound && <audio ref={successAudioRef} src={successSound} preload="auto" />}

      {justConfirmed && (
        <div className="card p-4 mb-6 border-green-800 bg-green-950/30">
          <p className="text-green-400 font-semibold">✓ Thank you! Your support has been confirmed and a receipt sent to your email.</p>
        </div>
      )}

      <div className="card p-6 text-center mb-6">
        <h1 className="text-2xl font-bold mb-2">Support the Creators</h1>
        <p className="text-neutral-400 text-sm">
          We share daily devotional content to help people grow in faith. Your optional support keeps this work going.
        </p>
      </div>

      <div className="card p-6 mb-4">
        <h3 className="font-semibold mb-3 flex items-center gap-2">
          <span className="w-6 h-6 rounded-full bg-red-900/50 text-red-400 flex items-center justify-center text-xs font-bold">1</span>
          Choose your support amount
        </h3>
        <div className="grid grid-cols-3 gap-2 mb-2">
          {presetAmounts.map((b) => (
            <button
              key={b.amount}
              onClick={() => pickNormal(b.amount)}
              className={`py-2.5 rounded-lg border text-sm font-semibold transition-colors ${
                selection?.source === "normal" && selection.amount === b.amount ? "bg-red-600 border-red-600" : "border-neutral-700 hover:border-neutral-500"
              }`}
            >
              {b.emoji ? `${b.emoji} ` : ""}${b.amount}
            </button>
          ))}
          <button
            onClick={pickCustom}
            className={`py-2.5 rounded-lg border text-sm font-semibold transition-colors col-span-3 sm:col-span-1 ${
              selection?.source === "custom" ? "bg-red-600 border-red-600" : "border-neutral-700 hover:border-neutral-500"
            }`}
          >
            {otherLabel}
          </button>
        </div>
        {selection?.source === "custom" && (
          <input
            type="number"
            min="1"
            step="0.01"
            placeholder="Enter amount"
            value={customAmount}
            onChange={(e) => setCustomAmount(e.target.value)}
            className="w-full bg-neutral-900 border border-neutral-800 rounded-lg px-3 py-2 text-sm outline-none focus:border-red-600 mt-2"
          />
        )}
      </div>

      {humbleEnabled && (
        <div className="card p-6 mb-4">
          <h3 className="font-semibold mb-3 text-sm text-neutral-300">💛 {humbleTitle}</h3>
          <button
            onClick={pickHumble}
            className={`w-full py-2.5 rounded-lg border text-sm font-semibold transition-colors ${
              selection?.source === "humble" ? "bg-red-600 border-red-600" : "border-neutral-700 hover:border-neutral-500"
            }`}
          >
            ${humbleAmount}
          </button>
        </div>
      )}

      {vipPresetAmounts.length > 0 && (
        <div className="card p-6 mb-4 border-amber-800/50 bg-gradient-to-br from-amber-950/20 to-transparent">
          <h3 className="font-semibold mb-1 flex items-center gap-2">
            <span className="w-6 h-6 rounded-full bg-amber-900/50 text-amber-400 flex items-center justify-center text-xs font-bold">★</span>
            {vipBoxTitle}
          </h3>
          <p className="text-xs text-neutral-500 mb-3">Choosing an amount here deselects your choice above — pick just one.</p>
          <div className="grid grid-cols-3 gap-2">
            {vipPresetAmounts.map((b) => (
              <button
                key={b.amount}
                onClick={() => pickVip(b.amount)}
                className={`py-2.5 rounded-lg border text-sm font-semibold transition-all ${
                  selection?.source === "vip" && selection.amount === b.amount
                    ? "bg-gradient-to-r from-amber-500 to-red-600 border-amber-500 scale-105"
                    : "border-amber-800/50 hover:border-amber-600"
                }`}
              >
                {b.emoji ? `${b.emoji} ` : ""}${b.amount}
              </button>
            ))}
          </div>
        </div>
      )}

      <div className="card p-6 mb-4">
        <h3 className="font-semibold mb-3 flex items-center gap-2">
          <span className="w-6 h-6 rounded-full bg-red-900/50 text-red-400 flex items-center justify-center text-xs font-bold">2</span>
          Your name and message
        </h3>
        <label className="block text-xs text-neutral-500 mb-1">Your name *</label>
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="How we should thank you"
          className="w-full bg-neutral-900 border border-neutral-800 rounded-lg px-3 py-2 text-sm outline-none focus:border-red-600 mb-3"
        />
        <label className="block text-xs text-neutral-500 mb-1">Message (optional)</label>
        <textarea
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="Share why you're giving..."
          rows={3}
          className="w-full bg-neutral-900 border border-neutral-800 rounded-lg px-3 py-2 text-sm outline-none focus:border-red-600"
        />
        {!loggedIn && (
          <>
            <label className="block text-xs text-neutral-500 mb-1 mt-3">Email (optional — for a receipt)</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com"
              className="w-full bg-neutral-900 border border-neutral-800 rounded-lg px-3 py-2 text-sm outline-none focus:border-red-600"
            />
          </>
        )}
      </div>

      <div className="card p-6 mb-4 space-y-3">
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={isPrivate} onChange={(e) => setIsPrivate(e.target.checked)} />
          Keep my message private
        </label>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={isRecurring} onChange={(e) => setIsRecurring(e.target.checked)} />
          Make this monthly support
        </label>
      </div>

      <p className="text-xs text-neutral-500 text-center mb-4">
        Donations are voluntary and do not unlock paid content or memberships.
      </p>

      {error && <p className="text-red-500 text-sm text-center mb-3">{error}</p>}

      <button onClick={handleSubmit} disabled={loading || finalAmount <= 0} className="btn-primary w-full py-3 mb-10">
        {loading ? "Redirecting..." : "Continue to secure payment"}
      </button>

      {supporters.length > 0 && (
        <div className="card p-6">
          <h3 className="font-bold mb-1">Partners in Mission</h3>
          <p className="text-xs text-neutral-500 mb-4">Generous hearts who supported us. Thank you for your support.</p>
          <div className="space-y-3">
            {supporters.map((s, i) => (
              <div key={i} className="flex items-center justify-between text-sm border-b border-neutral-800 pb-2 last:border-0">
                <div>
                  <span className="font-semibold">{s.name}</span>
                  {s.isRecurring && <span className="ml-2 text-xs text-amber-400">★ Monthly</span>}
                </div>
                <span className="text-neutral-500 text-xs">{new Date(s.createdAt).toLocaleDateString()}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
