"use client";

import React from "react";
import { useToast } from "@/app/components/ui/ToastProvider";

export function SendMessageForm({ receiverId, receiverNickname, onSent }: { receiverId: string; receiverNickname?: string | null; onSent?: () => void }) {
  const { show } = useToast();
  const [body, setBody] = React.useState("");
  const [sending, setSending] = React.useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!body.trim()) {
      show("메시지를 입력하세요");
      return;
    }
    setSending(true);
    try {
      const r = await fetch("/api/messages", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ receiverId, body }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) {
        const msg =
          j?.error?.message ||
          (j?.error?.fieldErrors ? Object.values(j.error.fieldErrors as any)[0]?.[0] : null) ||
          j?.error ||
          "전송 실패";
        throw new Error(msg);
      }
      setBody("");
      show("쪽지를 보냈습니다");
      onSent?.();
    } catch (e: any) {
      show(e?.message || "전송 실패");
    } finally {
      setSending(false);
    }
  }

  return (
    <form onSubmit={onSubmit} className="flex flex-col gap-2">
      <div className="text-sm text-neutral-700">
        받는 사람: <span className="font-semibold">{receiverNickname || "알 수 없음"}</span>
      </div>
      <textarea
        value={body}
        onChange={(e) => setBody(e.target.value)}
        placeholder="메시지를 입력하세요"
        className="w-full min-h-[96px] rounded-md border border-neutral-300 p-3 text-sm"
        maxLength={2000}
      />
      <div className="flex items-center gap-2 justify-end">
        <button
          type="submit"
          disabled={sending}
          className="h-9 px-4 rounded-md bg-neutral-900 text-white text-sm hover:bg-neutral-800 disabled:opacity-50"
        >
          {sending ? "전송 중..." : "쪽지 보내기"}
        </button>
      </div>
    </form>
  );
}


