"use client";

import { useState } from "react";
import { signIn } from "next-auth/react";

export default function SignupPage() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [slug, setSlug] = useState("storeshifted");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSignup(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage("");
    try {
      const res = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, password, slug }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Sign up failed");

      await signIn("credentials", {
        email,
        password,
        redirect: true,
        callbackUrl: "/connect",
      });
    } catch (err: any) {
      setMessage(err.message || "Sign up failed.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="auth-page">
      <section className="section">
        <div className="container auth-page__inner">
          <h1 className="page-title">Create Account</h1>
          <form className="auth-card" onSubmit={handleSignup}>
            <input
              type="text"
              placeholder="Name"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <input
              type="email"
              placeholder="Email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <input
              type="password"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <input
              type="text"
              placeholder="Store slug (e.g. storeshifted)"
              value={slug}
              onChange={(e) => setSlug(e.target.value)}
            />
            <button className="btn" type="submit" disabled={loading}>
              {loading ? "Creating..." : "Create account"}
            </button>
            {message ? <div className="connect-message">{message}</div> : null}
          </form>
          <div className="connect-muted">
            Already have an account? <a href="/login">Sign in</a>
          </div>
        </div>
      </section>
    </main>
  );
}
