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

import { useAuth } from "@/auth/AuthProvider";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { inTheme } from "@/theme";
import { inThemeVars } from "@/theme-vars";

export function LoginPage() {
  const { authenticating, login, user } = useAuth();
  const location = useLocation();
  const [email, setEmail] = useState("operator@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 ?? "/";
    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(--in-shell-bg)] px-6 py-12 text-[var(--in-text)]" style={inThemeVars(inTheme)}>
      <div className="mx-auto grid max-w-6xl gap-10 lg:grid-cols-[1.05fr_430px] lg:items-center">
        <div>
          <p className="inline-flex rounded-full bg-[var(--in-accent-soft)] px-4 py-2 text-sm font-semibold text-[var(--in-accent)]">
            IN operator workspace
          </p>
          <h1 className="mt-6 text-5xl font-black tracking-[-0.05em]">상담 흐름과 운영 상태를 동시에 여는 로그인 템플릿</h1>
          <p className="mt-5 max-w-xl text-lg leading-8 text-[var(--in-muted)]">
            `VITE_API_BASE_URL/auth/login`으로 인증한 뒤 `auth/me`를 재호출해 권한과 사용자 surface를 맞춘다.
          </p>
        </div>

        <Card className="p-7 shadow-[0_24px_70px_rgba(25,54,46,0.08)]">
          <form className="space-y-5" onSubmit={handleSubmit}>
            <div>
              <p className="text-2xl font-black">Sign in to IN</p>
              <p className="mt-2 text-sm text-[var(--in-muted)]">예시 계정은 `operator@example.com`이다.</p>
            </div>

            <label className="block space-y-2">
              <span className="text-sm font-semibold">Email</span>
              <Input type="email" value={email} onChange={(event) => setEmail(event.target.value)} required />
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-semibold">Password</span>
              <Input type="password" value={password} onChange={(event) => setPassword(event.target.value)} required />
            </label>

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

            <Button className="w-full" size="lg" type="submit" disabled={authenticating}>
              {authenticating ? "Signing in..." : "Continue to IN"}
            </Button>
          </form>
        </Card>
      </div>
    </div>
  );
}
