"use client";

import { useState } from "react";
import { Card, Button, Input } from "@/shared/components";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function RegisterPage() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleRegister = async (e) => {
    e.preventDefault();
    setError("");
    setSuccess("");

    // Client-side validation
    const trimmed = username.trim();
    if (trimmed.length < 3) {
      setError("Username must be at least 3 characters");
      return;
    }
    if (trimmed.length > 30) {
      setError("Username must be at most 30 characters");
      return;
    }
    if (password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }
    if (password !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username: trimmed, password }),
      });

      const data = await res.json();

      if (res.status === 201) {
        setSuccess("Registration submitted successfully. Await admin approval.");
      } else if (res.status === 409) {
        setError("Username already taken");
      } else if (res.status === 400) {
        setError(data.error || "Validation failed");
      } else {
        setError(data.error || "Registration failed");
      }
    } catch (err) {
      setError("An error occurred. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  // Success state
  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-bg p-4 relative overflow-hidden">
        <div className="landing-grid absolute inset-0 pointer-events-none" aria-hidden="true" />
        <div className="relative z-10 w-full max-w-md">
          <div className="text-center mb-8">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/kentutai-icon.png" alt="KentutAI" className="w-16 h-16 mx-auto mb-4 object-contain" />
            <h1 className="text-3xl font-bold text-primary mb-2">KentutAI</h1>
            <p className="text-text-muted">Create your KentutAI account</p>
          </div>
          <Card>
            <div className="flex flex-col items-center gap-4 py-4" data-testid="register-success">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-500/10 text-green-500">
                <span className="material-symbols-outlined text-[32px]">check_circle</span>
              </div>
              <p className="text-text-main font-medium text-center">{success}</p>
              <Link href="/login">
                <Button variant="primary">Go to Login</Button>
              </Link>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-bg p-4 relative overflow-hidden">
      {/* Faint grid background */}
      <div className="landing-grid absolute inset-0 pointer-events-none" aria-hidden="true" />
      <div className="relative z-10 w-full max-w-md">
        <div className="text-center mb-8">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src="/kentutai-icon.png" alt="KentutAI" className="w-16 h-16 mx-auto mb-4 object-contain" />
          <h1 className="text-3xl font-bold text-primary mb-2">KentutAI</h1>
          <p className="text-text-muted">Create your KentutAI account</p>
        </div>

        <Card>
          <form onSubmit={handleRegister} className="flex flex-col gap-4">
            <div className="flex flex-col gap-1">
              <Input
                label="Username"
                type="text"
                placeholder="Choose a username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
                autoFocus
                data-testid="register-username"
              />
            </div>

            <div className="flex flex-col gap-1">
              <Input
                label="Password"
                type="password"
                placeholder="At least 8 characters"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                data-testid="register-password"
              />
            </div>

            <div className="flex flex-col gap-1">
              <Input
                label="Confirm Password"
                type="password"
                placeholder="Re-enter your password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
                data-testid="register-confirm"
              />
            </div>

            {error && (
              <p className="text-xs text-red-500 flex items-center gap-1" data-testid="register-error">
                <span className="material-symbols-outlined text-[14px]">error</span>
                {error}
              </p>
            )}

            <Button
              type="submit"
              variant="primary"
              fullWidth
              loading={loading}
              data-testid="register-submit"
            >
              Register
            </Button>

            <p className="text-sm text-center text-text-muted mt-2">
              Already have an account?{" "}
              <Link href="/login" className="text-primary hover:underline">
                Login
              </Link>
            </p>
          </form>
        </Card>
      </div>
    </div>
  );
}
