import { useState } from "react";
import { useNavigate, Form, Link } from "react-router";
import { authClient } from "~/lib/auth-client";
import { Input } from "~/components/ui/input";
import { Button } from "~/components/ui/button";

export default function Login() {
  const navigate = useNavigate();
  const [error, setError] = useState<string | null>(null);
  const [pending, setPending] = useState(false);

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    setError(null);
    setPending(true);

    const formData = new FormData(event.currentTarget);

    const { error } = await authClient.signIn.email({
      email: String(formData.get("email")),
      password: String(formData.get("password")),
    });

    setPending(false);

    if (error) {
      setError(error.message ?? "Could not log in.");
      return;
    }

    navigate("/");
  }

  return (
    <main className="flex h-screen w-full items-center justify-center">
      <div className="w-full max-w-sm space-y-4">
        <div className="flex flex-col">
          <span className="text-2xl font-semibold">Log in</span>
          <span className="text-sm text-muted-foreground">
            Continue to Coppie.
          </span>
        </div>

        <Form onSubmit={onSubmit} className="space-y-4">
          <Input name="email" type="email" placeholder="Email" required />

          <Input
            name="password"
            type="password"
            placeholder="Password"
            required
          />

          {error ? <p className="text-sm text-red-600">{error}</p> : null}

          <Button type="submit" disabled={pending} className="w-full">
            {pending ? "Logging in..." : "Log in"}
          </Button>
        </Form>

        <p className="text-sm">
          No account?{" "}
          <Link to="/signup" className="underline">
            Sign up
          </Link>
        </p>
      </div>
    </main>
  );
}
