import Link from "next/link";
"use client";
import React from "react";
import { Button } from "@/app/components/ui/Button";
import { useToast } from "@/app/components/ui/ToastProvider";

export default function LoginPage() {
  const { show } = useToast();
  const [nickname, setNickname] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/auth/session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ nickname, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "로그인 실패");
      show("로그인되었습니다");
      location.href = "/";
    } catch (err: any) {
      show(err.message || "로그인 실패");
    } finally {
      setLoading(false);
    }
  };
  return (
    <div style={{ maxWidth: 420, margin: "40px auto" }}>
      <h1>로그인</h1>
      <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <input
          placeholder="닉네임"
          value={nickname}
          onChange={(e) => setNickname(e.target.value)}
          style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }}
        />
        <input
          placeholder="비밀번호"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }}
        />
        <Button type="submit" disabled={loading}>{loading ? "로그인 중..." : "로그인"}</Button>
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <Link href="/register">회원가입</Link>
        </div>
      </form>
    </div>
  );
}


