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

export default function RegisterPage() {
  const { show } = useToast();
  const [form, setForm] = React.useState({
    nickname: "",
    name: "",
    phone: "",
    birth: "",
    password: "",
    confirmPassword: "",
    agreeTerms: false,
  });
  const [loading, setLoading] = React.useState(false);
  const [errors, setErrors] = React.useState<Record<string, string[]>>({});
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setForm((f) => ({ ...f, [name]: type === "checkbox" ? checked : value }));
  };
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) {
        const fieldErrors = (data?.error?.fieldErrors ?? {}) as Record<string, string[]>;
        setErrors(fieldErrors);
        const msg = data?.error?.message || Object.values(fieldErrors)[0]?.[0] || "회원가입 실패";
        throw new Error(msg);
      }
      setErrors({});
      show("회원가입 성공! 로그인해주세요");
      location.href = "/login";
    } catch (err: any) {
      show(err.message || "회원가입 실패");
    } finally {
      setLoading(false);
    }
  };
  return (
    <div style={{ maxWidth: 480, margin: "40px auto" }}>
      <h1>회원가입</h1>
      <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <input name="nickname" placeholder="닉네임" value={form.nickname} onChange={onChange} aria-invalid={!!errors.nickname} aria-describedby="err-nickname" style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        {errors.nickname?.length ? (
          <span id="err-nickname" style={{ color: "#c00", fontSize: 12 }}>{errors.nickname[0]}</span>
        ) : null}
        <input name="name" placeholder="이름" value={form.name} onChange={onChange} aria-invalid={!!errors.name} aria-describedby="err-name" style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        {errors.name?.length ? (
          <span id="err-name" style={{ color: "#c00", fontSize: 12 }}>{errors.name[0]}</span>
        ) : null}
        <input name="phone" placeholder="전화번호" value={form.phone} onChange={onChange} aria-invalid={!!errors.phone} aria-describedby="err-phone" style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        {errors.phone?.length ? (
          <span id="err-phone" style={{ color: "#c00", fontSize: 12 }}>{errors.phone[0]}</span>
        ) : null}
        <input name="birth" placeholder="생년월일 (YYYY-MM-DD)" value={form.birth} onChange={onChange} aria-invalid={!!errors.birth} aria-describedby="err-birth" style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        {errors.birth?.length ? (
          <span id="err-birth" style={{ color: "#c00", fontSize: 12 }}>{errors.birth[0]}</span>
        ) : null}
        <input name="password" placeholder="비밀번호" type="password" value={form.password} onChange={onChange} aria-invalid={!!errors.password} aria-describedby="err-password" style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        {errors.password?.length ? (
          <span id="err-password" style={{ color: "#c00", fontSize: 12 }}>{errors.password[0]}</span>
        ) : null}
        <input name="confirmPassword" placeholder="비밀번호 확인" type="password" value={form.confirmPassword} onChange={onChange} aria-invalid={!!errors.confirmPassword} aria-describedby="err-confirmPassword" style={{ padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        {errors.confirmPassword?.length ? (
          <span id="err-confirmPassword" style={{ color: "#c00", fontSize: 12 }}>{errors.confirmPassword[0]}</span>
        ) : null}
        <label style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <input name="agreeTerms" type="checkbox" checked={form.agreeTerms} onChange={onChange} /> 약관에 동의합니다
        </label>
        <Button type="submit" disabled={loading}>{loading ? "가입 중..." : "가입하기"}</Button>
      </form>
    </div>
  );
}


