"use client";

import { useState } from "react";
import { useRouter } from "@/i18n/navigation";
import { startConversation } from "@/app/lib/chat";

interface SocialGreetButtonProps {
  profileId: string;
  label?: string;
  opener?: string;
  className?: string;
  onNeedLogin?: () => void;
}

export default function SocialGreetButton({
  profileId,
  label = "打招呼",
  opener = "你好，我在同城成员里看到你，想认识一下～",
  className = "rounded-full bg-[#ff4d4f] px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-500",
  onNeedLogin,
}: SocialGreetButtonProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  const handleClick = async () => {
    if (profileId.startsWith("fallback-")) {
      router.push("/dating");
      return;
    }
    setLoading(true);
    try {
      const conversation = await startConversation({ profileId, opener, intent: "friends" });
      router.push(`/chat/${conversation.id}`);
    } catch (err) {
      const message = err instanceof Error ? err.message : "";
      if (message.includes("登录") && onNeedLogin) {
        onNeedLogin();
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <button type="button" onClick={handleClick} disabled={loading} className={className}>
      {loading ? "连接中..." : label}
    </button>
  );
}
