"use client";

import { FormEvent, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { SunMoon } from "lucide-react";
import { useAppLocale } from "@/features/i18n/LocaleProvider";
import { getAuthMessages } from "@/features/i18n/messages/auth";

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

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

  const locale = useAppLocale();
  const { login: t } = getAuthMessages(locale);

  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 ?? t.errorLoginFailed);
        } catch {
          setError(t.errorLoginFailed);
        }
        setLoading(false);
        return;
      }

      // 성공 시에는 /dashboard 로 이동한다.
      router.push("/dashboard");
    } catch {
      setError(t.errorNetwork);
    } 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">{t.title}</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>{t.themeToggleLabel}</span>
          </button>
        </div>
        <p className="text-xs text-slate-500 mb-4 dark:text-slate-400">{t.description}</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">
              {t.emailLabel}
            </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">
              {t.passwordLabel}
            </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 ? t.submitLoading : t.submitIdle}
          </button>
        </form>

        <p className="mt-4 text-[11px] text-slate-500 dark:text-slate-400">
          {t.signupPromptPrefix}
          {" "}
          <Link href="/signup" className="text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
            {t.signupLinkText}
          </Link>
          {t.signupPromptSuffix && " "}
          {t.signupPromptSuffix}
        </p>
      </div>
    </main>
  );
}
