import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { login, register } from "./authApi";
import { setTokens, getToken, clearTokens } from "../../lib/auth";

type Mode = "login" | "register";

export function LoginPage() {
  const navigate = useNavigate();

  const [mode, setMode] = useState<Mode>("login");

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>("");
  const [success, setSuccess] = useState<string>("");

  const token = getToken();

  useEffect(() => {
    if (token) navigate("/expenses", { replace: true });
  }, [token, navigate]);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    setSuccess("");

    if (mode === "register" && password !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

    setLoading(true);
    try {
      if (mode === "register") {
        await register({ email, password });
        setSuccess("Registration successful. You can now log in.");
        setMode("login");
        setPassword("");
        setConfirmPassword("");
      } else {
        const res = await login({ email, password });
        setTokens(res.accessToken, res.refreshToken);
        navigate("/expenses", { replace: true });
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Request failed";
      setError(msg);
    } finally {
      setLoading(false);
    }
  }

  function onLogout() {
    clearTokens();
    setSuccess("Logged out. Token removed.");
    setError("");
    setEmail("");
    setPassword("");
    setConfirmPassword("");
  }

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-[radial-gradient(circle_at_top_right,#fce7f3_0%,#fbcfe8_28%,#ddd6fe_58%,#bfdbfe_100%)] p-6 text-rose-950">
      <div className="pointer-events-none absolute -left-24 top-16 h-72 w-72 rounded-full bg-pink-300/40 blur-3xl" />
      <div className="pointer-events-none absolute -right-28 bottom-12 h-80 w-80 rounded-full bg-violet-300/35 blur-3xl" />
      <div className="pointer-events-none absolute left-1/2 top-1/2 h-64 w-64 -translate-x-1/2 -translate-y-1/2 rounded-full bg-rose-200/45 blur-3xl" />

      <div className="relative w-full max-w-md rounded-3xl border border-rose-200/70 bg-white/50 p-7 shadow-[0_24px_80px_-28px_rgba(219,39,119,0.55)] backdrop-blur-xl">
        <div className="absolute right-5 top-5 rounded-full bg-rose-100/90 px-3 py-1 text-[10px] font-semibold uppercase tracking-widest text-rose-600">
          Pink Budget
        </div>

        <h1 className="text-3xl font-black tracking-tight text-rose-700">
          Expense Tracker
        </h1>
        <p className="mt-2 text-sm text-rose-700/80">
          Track your money with sparkle, style, and calm.
        </p>

        {token ? (
          <div className="mt-6 rounded-2xl border border-emerald-300/50 bg-emerald-100/70 p-4">
            <div className="text-sm text-emerald-900">You are logged in.</div>

            <button
              type="button"
              onClick={() => navigate("/expenses")}
              className="mt-4 w-full rounded-xl bg-linear-to-r from-rose-300 via-pink-300 to-violet-300 px-4 py-2 font-bold text-rose-900 shadow-lg shadow-rose-300/70 transition hover:scale-[1.01] hover:brightness-105"
            >
              Go to expenses
            </button>

            <button
              type="button"
              onClick={onLogout}
              className="mt-3 w-full rounded-xl border border-rose-200 bg-rose-100 px-4 py-2 font-semibold text-rose-700 transition hover:bg-rose-200"
            >
              Logout
            </button>
          </div>
        ) : (
          <>
            <div className="mt-6 grid grid-cols-2 gap-2 rounded-2xl border border-rose-200 bg-rose-50/70 p-1">
              <button
                type="button"
                onClick={() => {
                  setMode("login");
                  setError("");
                  setSuccess("");
                }}
                className={`rounded-xl px-3 py-2 text-sm font-bold transition ${
                  mode === "login"
                    ? "bg-pink-300/50 text-rose-800"
                    : "text-rose-700/80 hover:bg-pink-200/40"
                }`}
              >
                Login
              </button>
              <button
                type="button"
                onClick={() => {
                  setMode("register");
                  setError("");
                  setSuccess("");
                }}
                className={`rounded-xl px-3 py-2 text-sm font-bold transition ${
                  mode === "register"
                    ? "bg-pink-300/50 text-rose-800"
                    : "text-rose-700/80 hover:bg-pink-200/40"
                }`}
              >
                Register
              </button>
            </div>

            <form onSubmit={onSubmit} className="mt-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-rose-700">
                  Email
                </label>
                <input
                  className="mt-1 w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-pink-300 focus:ring-2 focus:ring-pink-200"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoComplete="email"
                  required
                  placeholder="you@example.com"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-rose-700">
                  Password
                </label>
                <input
                  className="mt-1 w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-fuchsia-300 focus:ring-2 focus:ring-fuchsia-200"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete={
                    mode === "login" ? "current-password" : "new-password"
                  }
                  required
                  minLength={6}
                  placeholder="Your secret passphrase"
                />
              </div>

              {mode === "register" ? (
                <div>
                  <label className="block text-sm font-medium text-rose-700">
                    Confirm password
                  </label>
                  <input
                    className="mt-1 w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-violet-300 focus:ring-2 focus:ring-violet-200"
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    autoComplete="new-password"
                    required
                    minLength={6}
                    placeholder="Repeat password"
                  />
                </div>
              ) : null}

              {error ? (
                <div className="rounded-xl border border-rose-300 bg-rose-100 p-3 text-sm text-rose-700">
                  {error}
                </div>
              ) : null}

              {success ? (
                <div className="rounded-xl border border-emerald-300 bg-emerald-100 p-3 text-sm text-emerald-700">
                  {success}
                </div>
              ) : null}

              <button
                type="submit"
                disabled={loading}
                className="w-full rounded-xl bg-linear-to-r from-rose-300 via-pink-300 to-violet-300 px-4 py-2 font-bold text-rose-900 shadow-lg shadow-rose-300/70 transition hover:scale-[1.01] hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60"
              >
                {loading
                  ? mode === "login"
                    ? "Logging in..."
                    : "Registering..."
                  : mode === "login"
                  ? "Login"
                  : "Register"}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}
