"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import Link from "next/link";

export default function RegisterPage() {
  const router = useRouter();
  const [name, setName] = useState("");
  const [orgName, setOrgName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const res = await fetch("/api/auth/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, orgName, email, password }),
    });
    const data = await res.json();
    if (!res.ok) {
      setError(data.error ?? "Something went wrong.");
      setLoading(false);
      return;
    }
    const signInRes = await signIn("credentials", { email, password, redirect: false });
    setLoading(false);
    if (signInRes?.error) {
      setError("Account created — please sign in.");
      router.push("/login");
      return;
    }
    router.push("/sites");
    router.refresh();
  }

  return (
    <div className="min-h-screen bg-bg flex items-center justify-center p-5">
      <div className="w-full max-w-[400px] bg-bg-card border border-border rounded-2xl p-8">
        <div className="flex items-center gap-2.5 mb-6">
          <div className="w-[30px] h-[30px] rounded-lg bg-gradient-to-br from-accent to-accent-2 flex-none" />
          <span className="font-heading font-bold text-lg tracking-tight">Webstation</span>
        </div>
        <div className="font-heading text-xl font-bold mb-1.5">Create your organization</div>
        <div className="text-[12.5px] text-text-secondary mb-5">
          You'll be the Owner — the only role that can manage billing and other Admins.
        </div>
        <form onSubmit={onSubmit} className="flex flex-col gap-3.5">
          <div>
            <label className="block text-xs text-text-secondary mb-1.5">Your name</label>
            <input
              required
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[13px] outline-none"
            />
          </div>
          <div>
            <label className="block text-xs text-text-secondary mb-1.5">Organization name</label>
            <input
              required
              value={orgName}
              onChange={(e) => setOrgName(e.target.value)}
              placeholder="BRJ Consulting"
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[13px] outline-none"
            />
          </div>
          <div>
            <label className="block text-xs text-text-secondary mb-1.5">Email</label>
            <input
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[13px] font-mono outline-none"
            />
          </div>
          <div>
            <label className="block text-xs text-text-secondary mb-1.5">Password</label>
            <input
              type="password"
              required
              minLength={8}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[13px] outline-none"
            />
          </div>
          {error && <div className="text-[12px] text-error">{error}</div>}
          <button
            type="submit"
            disabled={loading}
            className="w-full bg-accent text-white font-bold text-[13.5px] py-2.5 rounded-lg disabled:opacity-60"
          >
            {loading ? "Creating…" : "Create organization"}
          </button>
        </form>
        <div className="text-[11.5px] text-text-tertiary text-center mt-4">
          Already have an account?{" "}
          <Link href="/login" className="text-accent">
            Sign in
          </Link>
        </div>
      </div>
    </div>
  );
}
