"use client";

import { FormEvent, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

type PasswordStrengthLabel = "약함" | "보통" | "강함";

function getPasswordStrengthLabel(password: string): PasswordStrengthLabel | null {
  if (!password || password.length < 4) {
    return null;
  }

  let score = 0;
  if (/[a-z]/.test(password)) score += 1;
  if (/[A-Z]/.test(password)) score += 1;
  if (/[0-9]/.test(password)) score += 1;
  if (/[^a-zA-Z0-9]/.test(password)) score += 1;
  if (password.length >= 12) score += 1;

  if (password.length < 8 || score <= 2) {
    return "약함";
  }

  if (score === 3) {
    return "보통";
  }

  return "강함";
}

export default function SignupPage() {
  const router = useRouter();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [passwordConfirm, setPasswordConfirm] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;

    const checkAuth = async () => {
      try {
        const res = await fetch("/api/auth/me");
        if (!cancelled && res.ok) {
          router.push("/dashboard");
        }
      } catch {
        // ignore
      }
    };

    void checkAuth();

    return () => {
      cancelled = true;
    };
  }, [router]);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    setError(null);
    if (password !== passwordConfirm) {
      setError("비밀번호와 비밀번호 확인이 일치하지 않습니다.");
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });

      if (!res.ok) {
        try {
          const data = await res.json();
          setError(data?.message ?? "회원가입에 실패했습니다. 다시 시도해 주세요.");
        } catch {
          setError("회원가입에 실패했습니다. 다시 시도해 주세요.");
        }
        setLoading(false);
        return;
      }

      router.push("/dashboard");
    } catch {
      setError("네트워크 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
    } finally {
      setLoading(false);
    }
  };

  const strengthLabel = getPasswordStrengthLabel(password);

  return (
    <main className="min-h-screen flex items-center justify-center bg-slate-100 text-slate-900 dark:bg-slate-950 dark:text-slate-50">
      <div className="w-full max-w-sm rounded-lg border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-800 dark:bg-slate-900/70">
        <h1 className="text-lg font-semibold mb-1">회원가입</h1>
        <p className="text-xs text-slate-500 mb-4 dark:text-slate-400">새 계정을 생성한 뒤 프로젝트를 저장하고 관리할 수 있습니다.</p>

        {error && <p className="mb-3 text-xs text-red-300">{error}</p>}

        <form onSubmit={handleSubmit} className="space-y-3 text-xs">
          <div className="space-y-1">
            <label htmlFor="email" className="block text-slate-800 dark:text-slate-200">
              이메일
            </label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full rounded border border-slate-300 bg-white px-2 py-1 text-xs text-slate-900 focus:outline-none focus:ring-1 focus:ring-sky-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50"
              required
            />
          </div>

          <div className="space-y-1">
            <label htmlFor="password" className="block text-slate-800 dark:text-slate-200">
              비밀번호
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full rounded border border-slate-300 bg-white px-2 py-1 text-xs text-slate-900 focus:outline-none focus:ring-1 focus:ring-sky-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50"
              required
              minLength={8}
            />
          </div>

          {strengthLabel && (
            <div className="mt-1 space-y-1">
              <div className="h-1.5 rounded-full bg-slate-200/70 dark:bg-slate-700/70 overflow-hidden">
                <div
                  data-testid="password-strength-bar"
                  className={
                    "h-full transition-all " +
                    (strengthLabel === "약함"
                      ? "w-1/3 bg-red-500"
                      : strengthLabel === "보통"
                        ? "w-2/3 bg-amber-500"
                        : "w-full bg-emerald-600")
                  }
                />
              </div>
              <p
                className={
                  "text-[11px] " +
                  (strengthLabel === "약함"
                    ? "text-red-500 dark:text-red-300"
                    : strengthLabel === "보통"
                      ? "text-amber-500 dark:text-amber-300"
                      : "text-emerald-600 dark:text-emerald-300")
                }
              >
                비밀번호 난이도: {strengthLabel}
              </p>
            </div>
          )}

          <div className="space-y-1">
            <label htmlFor="passwordConfirm" className="block text-slate-800 dark:text-slate-200">
              비밀번호 확인
            </label>
            <input
              id="passwordConfirm"
              type="password"
              value={passwordConfirm}
              onChange={(e) => setPasswordConfirm(e.target.value)}
              className="w-full rounded border border-slate-300 bg-white px-2 py-1 text-xs text-slate-900 focus:outline-none focus:ring-1 focus:ring-sky-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50"
              required
              minLength={8}
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className="mt-2 w-full inline-flex items-center justify-center gap-1 rounded bg-sky-600 hover:bg-sky-500 disabled:opacity-40 disabled:cursor-not-allowed px-3 py-1 text-xs font-medium"
          >
            {loading ? "회원가입 중..." : "회원가입"}
          </button>
        </form>

        <p className="mt-4 text-[11px] text-slate-500 dark:text-slate-400">
          이미 계정이 있다면
          {" "}
          <Link href="/login" className="text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
            로그인
          </Link>
          으로 이동해 주세요.
        </p>
      </div>
    </main>
  );
}
