import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { login, setApiBase, getApiBase } from "@/lib/api";

export const Route = createFileRoute("/admin/login")({
  head: () => ({ meta: [{ title: "Admin — Komal Star" }, { name: "robots", content: "noindex" }] }),
  component: LoginPage,
});

function LoginPage() {
  const nav = useNavigate();
  const [apiBase, setBase] = useState(getApiBase());
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null); setBusy(true);
    try {
      if (apiBase) setApiBase(apiBase);
      if (!getApiBase()) throw new Error("Please enter your API base URL (e.g. https://yoursite.com/api)");
      await login(email, password);
      nav({ to: "/admin" });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Login failed");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="grid min-h-dvh place-items-center bg-slate-50 px-6">
      <form onSubmit={onSubmit} className="w-full max-w-md rounded-2xl border bg-white p-8 shadow-sm">
        <h1 className="font-display text-2xl font-bold">Komal Star Admin</h1>
        <p className="mt-1 text-sm text-muted-foreground">Sign in to manage products & blog.</p>

        <label className="mt-6 block text-sm font-medium">API base URL</label>
        <input value={apiBase} onChange={(e) => setBase(e.target.value)}
          placeholder="https://yourdomain.com/api"
          className="mt-1 w-full rounded-md border px-3 py-2 text-sm" />

        <label className="mt-4 block text-sm font-medium">Email</label>
        <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)}
          className="mt-1 w-full rounded-md border px-3 py-2 text-sm" />

        <label className="mt-4 block text-sm font-medium">Password</label>
        <input type="password" required value={password} onChange={(e) => setPassword(e.target.value)}
          className="mt-1 w-full rounded-md border px-3 py-2 text-sm" />

        {error && <p className="mt-4 rounded-md bg-red-50 p-3 text-sm text-red-700">{error}</p>}

        <button type="submit" disabled={busy}
          className="mt-6 w-full rounded-md bg-primary py-2.5 text-sm font-semibold text-primary-foreground disabled:opacity-60">
          {busy ? "Signing in…" : "Sign in"}
        </button>
      </form>
    </div>
  );
}
