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

export default function RegisterPage() {
  const { show } = useToast();
  const [form, setForm] = React.useState({
    nickname: "",
    name: "",
    password: "",
    confirmPassword: "",
    agreeTerms: false,
    profileImage: "" as string | undefined,
  });
  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) => {
      const next = { ...f, [name]: type === "checkbox" ? checked : value };
      // 비밀번호/확인 입력 시 일치하면 confirmPassword 에러 제거
      if (name === "password" || name === "confirmPassword") {
        setErrors((errs) => {
          const nextErrs = { ...errs };
          if (next.password === next.confirmPassword) {
            delete nextErrs.confirmPassword;
          } else if (next.password && next.confirmPassword) {
            nextErrs.confirmPassword = ["비밀번호가 일치하지 않습니다"];
          }
          return nextErrs;
        });
      }
      return next;
    });
  };
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // 클라이언트 가드: 비밀번호 불일치 시 제출 차단
    if (form.password !== form.confirmPassword) {
      setErrors((errs) => ({ ...errs, confirmPassword: ["비밀번호가 일치하지 않습니다"] }));
      return;
    }
    setLoading(true);
    try {
      // 닉네임 중복 선확인
      const checkRes = await fetch(`/api/auth/check-nickname?nickname=${encodeURIComponent(form.nickname)}`);
      if (!checkRes.ok) {
        const checkData = await checkRes.json().catch(() => ({}));
        const fieldErrors = (checkData?.error?.fieldErrors ?? {}) as Record<string, string[]>;
        if (Object.keys(fieldErrors).length) setErrors((prev) => ({ ...prev, ...fieldErrors }));
        const msg = checkData?.error?.message || fieldErrors.nickname?.[0] || "아이디 확인 실패";
        throw new Error(msg);
      } else {
        const check = await checkRes.json();
        if (!check.available) {
          setErrors((errs) => ({ ...errs, nickname: ["이미 사용 중인 아이디입니다"] }));
          throw new Error("이미 사용 중인 아이디입니다");
        }
      }

      // 닉네임(name) 중복 선확인
      const checkNameRes = await fetch(`/api/auth/check-name?name=${encodeURIComponent(form.name)}`);
      if (!checkNameRes.ok) {
        const checkNameData = await checkNameRes.json().catch(() => ({}));
        const fieldErrors = (checkNameData?.error?.fieldErrors ?? {}) as Record<string, string[]>;
        if (Object.keys(fieldErrors).length) setErrors((prev) => ({ ...prev, ...fieldErrors }));
        const msg = checkNameData?.error?.message || fieldErrors.name?.[0] || "닉네임 확인 실패";
        throw new Error(msg);
      } else {
        const check = await checkNameRes.json();
        if (!check.available) {
          setErrors((errs) => ({ ...errs, name: ["이미 사용 중인 닉네임입니다"] }));
          throw new Error("이미 사용 중인 닉네임입니다");
        }
      }

      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          // 빈 문자열은 undefined로 치환하여 검증을 단순화
          profileImage: form.profileImage ? form.profileImage : undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        if (res.status === 409) {
          const fieldErrors = (data?.error?.fieldErrors ?? {}) as Record<string, string[]>;
          if (fieldErrors.nickname?.length || fieldErrors.name?.length) {
            setErrors((errs) => ({ ...errs, ...fieldErrors }));
            const msg = fieldErrors.nickname?.[0] || fieldErrors.name?.[0] || "회원가입 실패";
            throw new Error(msg);
          } else {
            setErrors((errs) => ({ ...errs, nickname: ["이미 사용 중인 아이디입니다"] }));
            throw new Error("이미 사용 중인 아이디입니다");
          }
        }
        const fieldErrors = (data?.error?.fieldErrors ?? {}) as Record<string, string[]>;
        if (Object.keys(fieldErrors).length) setErrors(fieldErrors);
        const msg = data?.error?.message || Object.values(fieldErrors)[0]?.[0] || "회원가입 실패";
        throw new Error(msg);
      }
      setErrors({});
      show("회원가입이 완료되었습니다");
      setTimeout(() => {
        location.href = "/login";
      }, 1200);
    } 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 }}>
        {/* 프로필 이미지 업로드/미리보기 */}
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <UserAvatar src={form.profileImage || null} alt={form.name || "프로필"} width={64} height={64} className="rounded-full" />
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <UploadButton
              onUploaded={(url) => setForm((f) => ({ ...f, profileImage: url }))}
              aspectRatio={1}
              maxWidth={512}
              maxHeight={512}
              quality={0.9}
            />
            {form.profileImage ? (
              <button
                type="button"
                onClick={() => setForm((f) => ({ ...f, profileImage: "" }))}
                style={{ fontSize: 12, color: "#666", textDecoration: "underline", alignSelf: "flex-start", background: "transparent", border: 0, padding: 0, cursor: "pointer" }}
              >
                이미지 제거
              </button>
            ) : null}
            <span style={{ fontSize: 12, color: "#666" }}>프로필 이미지는 선택 사항입니다</span>
            {errors.profileImage?.length ? (
              <span id="err-profileImage" style={{ color: "#c00", fontSize: 12 }}>{errors.profileImage[0]}</span>
            ) : null}
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <input name="nickname" placeholder="아이디 (2~20자)" value={form.nickname} onChange={onChange} aria-invalid={!!errors.nickname} aria-describedby="err-nickname" style={{ flex: 1, padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        </div>
        {errors.nickname?.length ? (
          <span id="err-nickname" style={{ color: "#c00", fontSize: 12 }}>{errors.nickname[0]}</span>
        ) : null}
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <input name="name" placeholder="닉네임 (1~50자)" value={form.name} onChange={onChange} aria-invalid={!!errors.name} aria-describedby="err-name" style={{ flex: 1, padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        </div>
        {errors.name?.length ? (
          <span id="err-name" style={{ color: "#c00", fontSize: 12 }}>{errors.name[0]}</span>
        ) : null}
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <input name="password" placeholder="비밀번호 (8~100자)" type="password" value={form.password} onChange={onChange} aria-invalid={!!errors.password} aria-describedby="err-password" style={{ flex: 1, padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        </div>
        {errors.password?.length ? (
          <span id="err-password" style={{ color: "#c00", fontSize: 12 }}>{errors.password[0]}</span>
        ) : null}
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <input name="confirmPassword" placeholder="비밀번호 확인" type="password" value={form.confirmPassword} onChange={onChange} aria-invalid={!!errors.confirmPassword} aria-describedby="err-confirmPassword" style={{ flex: 1, padding: 8, border: "1px solid #ddd", borderRadius: 6 }} />
        </div>
        {errors.confirmPassword?.length ? (
          <span id="err-confirmPassword" style={{ color: "#c00", fontSize: 12 }}>{errors.confirmPassword[0]}</span>
        ) : null}
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <textarea
            readOnly
            value={`[이용 약관]\n\n본 서비스 이용 시 커뮤니티 가이드라인을 준수해야 하며, 불법/유해 콘텐츠 게시 금지 등 운영 정책을 따릅니다.\n개인정보는 서비스 제공 및 보안 목적에 한해 처리되며, 자세한 내용은 개인정보 처리방침을 확인하세요.`}
            style={{ width: "100%", minHeight: 140, padding: 8, border: "1px solid #ddd", borderRadius: 6, resize: "vertical", background: "#fafafa" }}
          />
          <label style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <input
              type="checkbox"
              name="agreeTerms"
              checked={form.agreeTerms}
              onChange={onChange}
            />
            <span style={{ fontSize: 14, color: "#333" }}>약관에 동의합니다</span>
          </label>
          {errors.agreeTerms?.length ? (
            <span id="err-agree" style={{ color: "#c00", fontSize: 12 }}>{errors.agreeTerms[0]}</span>
          ) : null}
        </div>
        <Button type="submit" disabled={loading || form.password !== form.confirmPassword}>{loading ? "가입 중..." : "가입하기"}</Button>
      </form>
    </div>
  );
}


