"use client";

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

// 로그인 페이지 컴포넌트
// - 이메일/비밀번호를 입력받아 /api/auth/login 으로 요청을 전송한다.
// - 성공 시 /projects 로 이동하고, 실패 시 에러 메시지를 보여준다.

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

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

  const handleToggleTheme = () => {
    if (typeof document === "undefined") {
      return;
    }

    const root = document.documentElement;
    if (!root) {
      return;
    }

    root.classList.toggle("dark");
  };

  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);
    setLoading(true);

    try {
      const res = await fetch("/api/auth/login", {
        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;
      }

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

  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">
        <div className="flex items-center justify-between mb-1">
          <h1 className="text-lg font-semibold">로그인</h1>
          <button
            type="button"
            className="inline-flex items-center gap-1 rounded-full border border-slate-300 bg-white/80 px-2 py-1 text-[11px] font-medium text-slate-700 hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"
            onClick={handleToggleTheme}
          >
            <SunMoon className="w-4 h-4" aria-hidden="true" />
            <span>테마 전환</span>
          </button>
        </div>
        <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>

          <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="/signup" className="text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
            회원가입
          </Link>
          을 진행해 주세요.
        </p>
      </div>
    </main>
  );
}
