"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

interface LetsChatButtonProps {
  recipientId: number;
  recipientIdAw: string;
  messageCost: number | null;
}

export default function LetsChatButton({ recipientId, recipientIdAw, messageCost }: LetsChatButtonProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  async function handleClick() {
    setLoading(true);
    try {
      const res = await fetch("/api/messages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          recipient_id: recipientId,
          body: "Hi! I'd like to chat.",
        }),
      });

      if (res.ok) {
        const data = await res.json();
        const roomId = data.data?.room_id;
        if (roomId) {
          router.push(`/messages/${roomId}`);
        } else {
          // Fallback: go to messages with recipient param
          router.push(`/messages?recipient=${recipientId}`);
        }
      } else if (res.status === 402) {
        const data = await res.json();
        alert(`Insufficient credits. Messaging this escort costs ${data.cost} credits per message.`);
      } else {
        router.push(`/messages?recipient=${recipientId}`);
      }
    } catch {
      router.push(`/messages?recipient=${recipientId}`);
    } finally {
      setLoading(false);
    }
  }

  const showCost = messageCost && messageCost > 0;

  return (
    <button
      onClick={handleClick}
      disabled={loading}
      className="inline-flex items-center gap-2 bg-gold hover:bg-gold-light text-black font-semibold px-5 py-2.5 rounded-lg transition-all duration-200 shadow-glow hover:shadow-lg text-sm disabled:opacity-50"
    >
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
        />
      </svg>
      {loading ? (
        "Starting chat..."
      ) : showCost ? (
        <>
          Let&apos;s Chat!{" "}
          <span className="text-gold-dark">({messageCost} credit/msg)</span>
        </>
      ) : (
        "Let's Chat!"
      )}
    </button>
  );
}
