"use client";

import { useState, useCallback, useRef } from "react";
import { useSession } from "next-auth/react";
import { vibrate } from "@/lib/haptics";

interface MicroTipProps {
  receiverId: number;
}

const REACTIONS = [
  { emoji: "\u{1F525}", label: "Fire", amount: 1 },
  { emoji: "\u2764\uFE0F", label: "Love", amount: 2 },
  { emoji: "\u{1F48E}", label: "Diamond", amount: 5 },
  { emoji: "\u{1F451}", label: "Crown", amount: 10 },
] as const;

export default function MicroTip({ receiverId }: MicroTipProps) {
  const { data: session } = useSession();
  const [sending, setSending] = useState<number | null>(null);
  const [poppedIdx, setPoppedIdx] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleTip = useCallback(
    async (amount: number, idx: number) => {
      if (!session?.user || sending !== null) return;

      setSending(idx);
      setError(null);
      setPoppedIdx(idx);

      // Clear previous animation timeout
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
      timeoutRef.current = setTimeout(() => setPoppedIdx(null), 600);

      try {
        const res = await fetch("/api/tips", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ receiver_id: receiverId, amount }),
        });

        if (!res.ok) {
          const data = await res.json();
          setError(data.error || "Failed to send tip");
        } else {
          vibrate([10, 30, 10]);
        }
      } catch {
        setError("Failed to send tip");
      } finally {
        setSending(null);
      }
    },
    [receiverId, session, sending]
  );

  const isDisabled = !session?.user;

  return (
    <div className="flex items-center gap-1">
      {REACTIONS.map((reaction, idx) => (
        <button
          key={reaction.label}
          onClick={() => handleTip(reaction.amount, idx)}
          disabled={isDisabled || sending !== null}
          title={
            isDisabled
              ? "Log in to send a reaction"
              : `${reaction.label} (${reaction.amount} credit${reaction.amount > 1 ? "s" : ""})`
          }
          className={`
            relative flex items-center gap-1 px-2 py-1 rounded-full text-sm
            border border-surface-light bg-surface-light/50
            hover:bg-gold/10 hover:border-gold/30
            disabled:opacity-40 disabled:cursor-not-allowed
            transition-all duration-150
            ${sending === idx ? "scale-95 opacity-70" : ""}
          `}
        >
          <span
            className={`
              inline-block transition-transform duration-300
              ${poppedIdx === idx ? "animate-micro-tip-pop" : ""}
            `}
          >
            {reaction.emoji}
          </span>
          <span className="text-text-muted text-xs">{reaction.amount}</span>

          {/* Particle animation overlay */}
          {poppedIdx === idx && (
            <span className="absolute inset-0 flex items-center justify-center pointer-events-none">
              <span className="absolute animate-micro-tip-particle-1 text-xs opacity-0">
                {reaction.emoji}
              </span>
              <span className="absolute animate-micro-tip-particle-2 text-xs opacity-0">
                {reaction.emoji}
              </span>
              <span className="absolute animate-micro-tip-particle-3 text-xs opacity-0">
                {reaction.emoji}
              </span>
            </span>
          )}
        </button>
      ))}
      {error && (
        <span className="text-red-400 text-xs ml-1">{error}</span>
      )}

      {/* Keyframe styles injected inline for the particle animations */}
      <style jsx global>{`
        @keyframes micro-tip-pop {
          0% { transform: scale(1); }
          30% { transform: scale(1.5); }
          60% { transform: scale(0.9); }
          100% { transform: scale(1); }
        }
        @keyframes micro-tip-particle-1 {
          0% { opacity: 1; transform: translate(0, 0) scale(1); }
          100% { opacity: 0; transform: translate(-12px, -18px) scale(0.5); }
        }
        @keyframes micro-tip-particle-2 {
          0% { opacity: 1; transform: translate(0, 0) scale(1); }
          100% { opacity: 0; transform: translate(14px, -16px) scale(0.4); }
        }
        @keyframes micro-tip-particle-3 {
          0% { opacity: 1; transform: translate(0, 0) scale(1); }
          100% { opacity: 0; transform: translate(2px, -22px) scale(0.3); }
        }
        .animate-micro-tip-pop {
          animation: micro-tip-pop 0.4s ease-out;
        }
        .animate-micro-tip-particle-1 {
          animation: micro-tip-particle-1 0.5s ease-out forwards;
        }
        .animate-micro-tip-particle-2 {
          animation: micro-tip-particle-2 0.5s ease-out 0.05s forwards;
        }
        .animate-micro-tip-particle-3 {
          animation: micro-tip-particle-3 0.5s ease-out 0.1s forwards;
        }
      `}</style>
    </div>
  );
}
