import { FormEvent, useState } from "react";
import { registerRequest } from "../api/auth";
import { useAuthStore } from "../store/authStore";

type Mode = "login" | "register";

export function AuthPanel() {
  const login = useAuthStore((s) => s.login);
  const loading = useAuthStore((s) => s.loading);
  const [mode, setMode] = useState<Mode>("login");
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    setError(null);
    setSuccess(null);
    try {
      if (mode === "register") {
        await registerRequest(email, name, username, password);
        setSuccess("Registered. Check email verification, then login.");
        setMode("login");
        return;
      }
      await login(email, password);
    } catch {
      setError("Auth request failed.");
    }
  }

  return (
    <div className="mx-auto mt-16 w-full max-w-md rounded-xl bg-panel p-6 shadow-xl">
      <div className="mb-4 flex gap-2">
        <button className={`rounded px-3 py-2 ${mode === "login" ? "bg-accent text-black" : "bg-slate-700"}`} onClick={() => setMode("login")}>
          Login
        </button>
        <button className={`rounded px-3 py-2 ${mode === "register" ? "bg-accent text-black" : "bg-slate-700"}`} onClick={() => setMode("register")}>
          Register
        </button>
      </div>
      <form className="space-y-3" onSubmit={onSubmit}>
        <input className="w-full rounded bg-slate-800 px-3 py-2" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
        {mode === "register" && (
          <>
            <input className="w-full rounded bg-slate-800 px-3 py-2" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
            <input className="w-full rounded bg-slate-800 px-3 py-2" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} />
          </>
        )}
        <input className="w-full rounded bg-slate-800 px-3 py-2" placeholder="Password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
        <button className="w-full rounded bg-accent px-3 py-2 font-semibold text-black disabled:opacity-50" disabled={loading} type="submit">
          {mode === "login" ? "Sign in" : "Create account"}
        </button>
      </form>
      {error ? <p className="mt-3 text-sm text-red-400">{error}</p> : null}
      {success ? <p className="mt-3 text-sm text-emerald-400">{success}</p> : null}
    </div>
  );
}
