"use client";

import { useState, type FormEvent } from "react";
import Link from "next/link";
import { GoogleOAuthProvider } from "@react-oauth/google";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/ui/password-input";
import { PasswordRequirementsChecklist } from "@/components/auth/password-requirements-checklist";
import { PasswordStrengthMeter } from "@/components/auth/password-strength-meter";
import { AuthDivider } from "@/components/auth/auth-divider";
import { GoogleAuthButton } from "@/components/auth/google-auth-button";
import { isPasswordValid } from "@/lib/password-validation";

const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? "";

export default function RegisterPage() {
  const [errors, setErrors] = useState<Record<string, string[]>>({});
  const [formError, setFormError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");

  const passwordValid = isPasswordValid(password);
  const passwordsMatch = passwordConfirmation.length > 0 && password === passwordConfirmation;

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setErrors({});
    setFormError(null);
    setIsSubmitting(true);

    const formData = new FormData(event.currentTarget);

    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.get("name"),
          email: formData.get("email"),
          phone: formData.get("phone") || null,
          date_of_birth: formData.get("date_of_birth"),
          password: formData.get("password"),
          password_confirmation: formData.get("password_confirmation"),
        }),
      });

      if (!res.ok) {
        const body = await res.json().catch(() => null);
        setErrors(body?.errors ?? {});
        setFormError(body?.message ?? "Registration failed.");
        setIsSubmitting(false);
        return;
      }

      // Full navigation, not router.push+refresh — see login/page.tsx for why.
      window.location.href = "/";
    } catch {
      setFormError("Unable to reach the server. Please check your connection and try again.");
      setIsSubmitting(false);
    }
  }

  function fieldError(name: string) {
    return errors[name]?.[0];
  }

  return (
    <div className="mx-auto flex min-h-[70vh] max-w-md flex-col justify-center px-6 py-12">
      <h1 className="text-2xl font-semibold">Create a Kolaborativ Account</h1>
      <p className="mt-1 text-sm text-kolabora-neutral-dark/70">
        Already have an account?{" "}
        <Link href="/login" className="font-medium text-kolabora-primary">
          Log in here
        </Link>
      </p>

      <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-4">
        <label className="flex flex-col gap-1 text-sm font-medium">
          Full Name
          <Input type="text" name="name" required />
          {fieldError("name") && <span className="text-xs text-red-600">{fieldError("name")}</span>}
        </label>

        <label className="flex flex-col gap-1 text-sm font-medium">
          Email
          <Input type="email" name="email" required />
          {fieldError("email") && <span className="text-xs text-red-600">{fieldError("email")}</span>}
        </label>

        <label className="flex flex-col gap-1 text-sm font-medium">
          Phone Number (optional)
          <Input type="tel" name="phone" />
        </label>

        <label className="flex flex-col gap-1 text-sm font-medium">
          Date of Birth
          <Input type="date" name="date_of_birth" required />
          {fieldError("date_of_birth") && (
            <span className="text-xs text-red-600">{fieldError("date_of_birth")}</span>
          )}
        </label>

        <div className="flex flex-col gap-1 text-sm font-medium">
          <label htmlFor="password">Password</label>
          <PasswordInput
            id="password"
            name="password"
            required
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            aria-describedby="password-requirements"
          />
          {fieldError("password") && <span className="text-xs text-red-600">{fieldError("password")}</span>}
          <PasswordStrengthMeter password={password} />
          <PasswordRequirementsChecklist password={password} id="password-requirements" />
        </div>

        <div className="flex flex-col gap-1 text-sm font-medium">
          <label htmlFor="password_confirmation">Confirm Password</label>
          <PasswordInput
            id="password_confirmation"
            name="password_confirmation"
            required
            value={passwordConfirmation}
            onChange={(event) => setPasswordConfirmation(event.target.value)}
            aria-describedby="password-match-status"
          />
          {passwordConfirmation.length > 0 && (
            <p
              id="password-match-status"
              aria-live="polite"
              className={`flex items-center gap-1 text-xs font-medium transition-colors duration-200 ${
                passwordsMatch ? "text-green-600" : "text-red-600"
              }`}
            >
              {passwordsMatch ? "✓ Passwords match" : "✕ Passwords do not match"}
            </p>
          )}
        </div>

        {formError && <p className="text-sm text-red-600">{formError}</p>}

        <Button type="submit" loading={isSubmitting} disabled={!passwordValid || !passwordsMatch} className="mt-2">
          Sign Up
        </Button>
      </form>

      {GOOGLE_CLIENT_ID && (
        <>
          <AuthDivider />

          <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
            <GoogleAuthButton label="Sign up with Google" onError={setFormError} />
          </GoogleOAuthProvider>
        </>
      )}
    </div>
  );
}
