"use client";

import { FormEvent, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { supabaseBrowser } from "@/lib/supabase/browser";

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

  const onSubmit = async (event: FormEvent) => {
    event.preventDefault();
    setError(null);
    setLoading(true);

    const client = supabaseBrowser();
    if (!client) {
      setLoading(false);
      setError("Supabase is not configured. Add NEXT_PUBLIC_SUPABASE_* to .env.local.");
      return;
    }

    const { error: signUpError } = await client.auth.signUp({ email, password });
    setLoading(false);

    if (signUpError) {
      setError(signUpError.message);
      return;
    }

    router.push("/courses");
  };

  return (
    <div className="acve-panel mx-auto w-full max-w-md p-6">
      <h1 className="acve-heading text-4xl">Sign up</h1>
      <p className="mt-1 text-base text-slate-600">Create your account to unlock course player and practice.</p>

      <form className="mt-5 space-y-4" onSubmit={onSubmit}>
        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Email</span>
          <input
            className="w-full rounded-xl border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            onChange={(event) => setEmail(event.target.value)}
            required
            type="email"
            value={email}
          />
        </label>

        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Password</span>
          <input
            className="w-full rounded-xl border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            minLength={6}
            onChange={(event) => setPassword(event.target.value)}
            required
            type="password"
            value={password}
          />
        </label>

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

        <button
          className="acve-button-primary w-full px-4 py-2 font-semibold hover:brightness-105 disabled:opacity-60"
          disabled={loading}
          type="submit"
        >
          {loading ? "Creating account..." : "Create account"}
        </button>
      </form>

      <p className="mt-4 text-sm text-slate-600">
        Already have an account?{" "}
        <Link className="font-semibold text-brand" href="/auth/login">
          Login
        </Link>
      </p>
    </div>
  );
}
