"use client";

import React from "react";
import Link from "next/link";

export function InlineLoginForm({ next = "/" }: { next?: string }) {
  const [nickname, setNickname] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/auth/session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: nickname, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data?.error || "로그인 실패");
      // 성공 시 다음 경로로 이동 (기본은 홈)
      window.location.href = next || "/";
    } catch (err: any) {
      const raw = err?.message;
      const fallback = "아이디 또는 비밀번호가 일치하지 않습니다";
      const msg =
        typeof raw === "string" && raw !== "[object Object]" && raw.trim().length > 0
          ? raw
          : fallback;
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={onSubmit} className="w-[300px] flex flex-col gap-2">
      <input
        placeholder="아이디"
        value={nickname}
        onChange={(e) => setNickname(e.target.value)}
        className="h-10 rounded-md border border-neutral-300 px-3 text-sm"
      />
      <input
        placeholder="비밀번호"
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        className="h-10 rounded-md border border-neutral-300 px-3 text-sm"
      />
      {error && <div className="text-xs text-red-600 mt-1">{error}</div>}
      <button
        type="submit"
        disabled={loading}
        className="w-full h-[40px] rounded-full bg-[#8c8c8c] hover:bg-[#5c5c5c] text-white text-[14px] font-[700] flex items-center justify-center disabled:opacity-60"
      >
        {loading ? "로그인 중..." : "로그인"}
      </button>
      <div className="flex justify-end">
        <Link href="/register" className="text-[13px] text-[#5c5c5c] hover:underline">회원가입</Link>
      </div>
    </form>
  );
}


