"use client";

import { ArrowRight, ShieldCheck } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { AuthAside } from "@/components/auth-aside";
import { Button, Field, Input } from "@/components/ui";
import { Wordmark } from "@/components/brand";
import { ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";

export default function LoginPage() {
  const { login, booting, isAuthed } = useAuth();
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!booting && isAuthed) router.replace("/dashboard");
  }, [booting, isAuthed, router]);

  return (
    <div className="grid min-h-screen lg:grid-cols-2">
      <AuthAside />
      <div className="flex items-center justify-center px-6 py-12">
        <div className="w-full max-w-sm animate-fade-up">
          <div className="lg:hidden">
            <Wordmark className="mb-8" />
          </div>
          <span className="eyebrow">Sign in</span>
          <h1 className="mt-2 font-display text-3xl font-bold tracking-tight text-fg">
            Welcome back
          </h1>
          <p className="mt-2 text-sm text-muted">
            Command your agents, workflows, and approvals.
          </p>

          <form
            className="mt-8 space-y-4"
            onSubmit={async (e) => {
              e.preventDefault();
              setError(null);
              setLoading(true);
              try {
                await login(email, password);
                router.replace("/dashboard");
              } catch (err) {
                setError(err instanceof ApiError ? err.message : "Sign in failed");
              } finally {
                setLoading(false);
              }
            }}
          >
            <Field label="Email">
              <Input
                type="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@company.com"
              />
            </Field>
            <Field label="Password">
              <Input
                type="password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
              />
            </Field>
            {error && (
              <div className="rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
                {error}
              </div>
            )}
            <Button variant="primary" size="lg" className="w-full" type="submit" loading={loading}>
              Sign in <ArrowRight className="h-4 w-4" />
            </Button>
          </form>

          <p className="mt-6 text-sm text-muted">
            No account?{" "}
            <Link href="/register" className="font-medium text-accent hover:underline">
              Create one
            </Link>
          </p>
          <div className="mt-8 flex items-center gap-2 text-xs text-faint">
            <ShieldCheck className="h-3.5 w-3.5" />
            Self-hosted · your data never leaves your infrastructure
          </div>
        </div>
      </div>
    </div>
  );
}
