import { useState } from "react";
import { Link, Navigate, useLocation } from "react-router-dom";

import { useAuth } from "@/auth/AuthProvider";
import { landingTheme } from "@/theme";
import { landingThemeVars } from "@/theme-vars";

export function LandingLoginPage() {
  const { authenticating, login, user } = useAuth();
  const location = useLocation();
  const [email, setEmail] = useState("admin@example.com");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);

  if (user) {
    const destination = (location.state as { from?: { pathname?: string } } | null)?.from?.pathname ?? "/workspace";
    return <Navigate to={destination} replace />;
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);

    try {
      await login({ email, password });
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : "로그인에 실패했습니다.");
    }
  }

  return (
    <div className="min-h-screen bg-[var(--landing-bg)] px-6 py-10 text-[var(--landing-text)]" style={landingThemeVars(landingTheme)}>
      <div className="mx-auto grid max-w-5xl overflow-hidden rounded-[36px] border border-[#eadbcb] bg-white shadow-[0_28px_80px_rgba(123,78,42,0.12)] lg:grid-cols-[1fr_420px]">
        <section className="bg-[#fff7ef] px-8 py-10 sm:px-12 sm:py-14">
          <p className="inline-flex rounded-full bg-[var(--landing-accent-soft)] px-4 py-2 text-sm font-semibold text-[var(--landing-accent)]">
            Member access
          </p>
          <h1 className="mt-7 text-4xl font-black tracking-[-0.04em] text-[#2c261f]">랜딩에서 바로 이어지는 로그인</h1>
          <p className="mt-5 max-w-md text-base leading-8 text-[var(--landing-muted)]">
            로그인 성공 시 토큰을 저장하고 보호된 `/workspace`로 이동합니다. 새로고침 후에도 `auth/me`로 세션을 복원합니다.
          </p>
          <Link className="mt-8 inline-flex rounded-full border border-[#d8cabb] px-5 py-3 text-sm font-semibold" to="/">
            Back to landing
          </Link>
        </section>

        <section className="px-8 py-10 sm:px-10 sm:py-14">
          <form className="space-y-5" onSubmit={handleSubmit}>
            <div>
              <p className="text-sm font-semibold uppercase tracking-[0.18em] text-[var(--landing-accent)]">Sign in</p>
              <h2 className="mt-3 text-3xl font-black text-[#2c261f]">Open workspace</h2>
            </div>

            <label className="block space-y-2">
              <span className="text-sm font-semibold text-[#5b5145]">Email</span>
              <input
                className="h-11 w-full rounded-xl border border-[#e2d5c7] px-4 text-sm outline-none focus:ring-2 focus:ring-[#e9c590]"
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                required
              />
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-semibold text-[#5b5145]">Password</span>
              <input
                className="h-11 w-full rounded-xl border border-[#e2d5c7] px-4 text-sm outline-none focus:ring-2 focus:ring-[#e9c590]"
                type="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                required
              />
            </label>

            {error ? <p className="text-sm font-medium text-[#c05b2d]">{error}</p> : null}

            <button
              className="inline-flex h-11 w-full items-center justify-center rounded-full bg-[#2c261f] px-5 text-sm font-semibold text-white disabled:opacity-60"
              disabled={authenticating}
              type="submit"
            >
              {authenticating ? "Signing in..." : "Continue"}
            </button>
          </form>
        </section>
      </div>
    </div>
  );
}
