import { useMutation } from "@tanstack/react-query";
import type { FormEvent } from "react";
import { useState } from "react";

import { api, type AuthState } from "../../api";

export function AuthScreen({ onAuth }: { onAuth: (auth: AuthState) => void }) {
  const [mode, setMode] = useState<"login" | "register">("login");
  const [email, setEmail] = useState("demo@example.com");
  const [password, setPassword] = useState("password123");
  const [displayName, setDisplayName] = useState("Demo Athlete");
  const [error, setError] = useState<string | null>(null);

  const mutation = useMutation({
    mutationFn: () =>
      mode === "login"
        ? api.login({ email, password })
        : api.register({ email, password, display_name: displayName }),
    onSuccess: onAuth,
    onError: (err) => setError(err.message),
  });

  function submit(event: FormEvent) {
    event.preventDefault();
    setError(null);
    mutation.mutate();
  }

  return (
    <main className="auth-layout">
      <section className="hero-panel" aria-label="Train Watcher intro">
        <p className="eyebrow">Live workout console</p>
        <h1>Один экран. Один подход. Весь прогресс под рукой.</h1>
        <p>
          Train Watcher теперь работает как живой журнал: стартуй сессию, добавляй упражнения через drawer и фиксируй каждый подход без ухода в каталог.
        </p>
      </section>
      <form className="card auth-card" onSubmit={submit}>
        <p className="eyebrow">{mode === "login" ? "Welcome back" : "New athlete"}</p>
        <h2>{mode === "login" ? "Вход" : "Регистрация"}</h2>
        {mode === "register" && (
          <label>
            Имя
            <input value={displayName} onChange={(event) => setDisplayName(event.target.value)} />
          </label>
        )}
        <label>
          Email
          <input type="email" autoComplete="username" value={email} onChange={(event) => setEmail(event.target.value)} />
        </label>
        <label>
          Пароль
          <input
            type="password"
            autoComplete={mode === "register" ? "new-password" : "current-password"}
            value={password}
            onChange={(event) => setPassword(event.target.value)}
          />
        </label>
        {error && <p className="error">{error}</p>}
        <button className="primary" disabled={mutation.isPending}>
          {mutation.isPending ? "Отправка..." : mode === "login" ? "Войти" : "Создать аккаунт"}
        </button>
        <button type="button" className="ghost" onClick={() => setMode(mode === "login" ? "register" : "login")}>
          {mode === "login" ? "Нужна регистрация" : "Уже есть аккаунт"}
        </button>
      </form>
    </main>
  );
}
