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

export default function Signup() {
  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.signUp.email({
      name: String(formData.get("name")),
      email: String(formData.get("email")),
      password: String(formData.get("password")),
    });

    setPending(false);

    if (error) {
      setError(error.message ?? "Could not create account.");
      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">Sign up</span>
          <span className="text-sm text-muted-foreground">
            Create your Coppie account.
          </span>
        </div>

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

          <Input name="email" type="email" placeholder="Email" required />

          <Input
            name="password"
            type="password"
            placeholder="Password"
            required
            minLength={8}
          />

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

          <Button type="submit" disabled={pending} className="w-full">
            {pending ? "Creating account..." : "Create account"}
          </Button>
        </Form>

        <p className="text-sm">
          Already have an account?{" "}
          <Link to="/login" className="underline">
            Log in
          </Link>
        </p>
      </div>
    </main>
  );
}
