"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useAuthContext } from "@/hooks/auth-context";

export default function RegisterPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const { register, loading } = useAuthContext();

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    const result = await register({ email, password, displayName });
    if (!result.ok) {
      setError(result.error || "Registration failed");
      return;
    }
    router.replace("/");
  }

  return (
    <div className="mx-auto max-w-sm space-y-4">
      <div className="flex items-center gap-2">
        <img
          src="/icons/navbar-settings.png"
          alt=""
          className="h-7 w-7 rounded-lg object-cover"
        />
        <h1 className="text-2xl font-semibold">Register</h1>
      </div>
      <form
        onSubmit={onSubmit}
        className="space-y-3 panel panel-accent p-4"
      >
        <label className="block text-sm text-muted">
          Email
          <input
            type="email"
            className="mt-1 w-full input-base px-3 py-2 text-sm"
            value={email}
            onChange={e => setEmail(e.target.value)}
            autoComplete="email"
            required
          />
        </label>
        <label className="block text-sm text-muted">
          Display name
          <input
            type="text"
            className="mt-1 w-full input-base px-3 py-2 text-sm"
            value={displayName}
            onChange={e => setDisplayName(e.target.value)}
            autoComplete="name"
          />
        </label>
        <label className="block text-sm text-muted">
          Password
          <input
            type="password"
            className="mt-1 w-full input-base px-3 py-2 text-sm"
            value={password}
            onChange={e => setPassword(e.target.value)}
            autoComplete="new-password"
            minLength={8}
            required
          />
        </label>
        {error ? <div className="text-sm text-red-400">{error}</div> : null}
        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-lg btn-accent px-3 py-2 text-sm font-semibold disabled:opacity-60"
        >
          {loading ? "Creating account..." : "Create account"}
        </button>
        <div className="text-center text-sm text-muted">
          Already have an account?{" "}
          <a href="/login" className="text-[color:var(--color-accent)]">
            Login
          </a>
        </div>
      </form>
    </div>
  );
}
