"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Container } from "@/components/layout/Container";
import { Input } from "@/components/ui/Input";
import { Button } from "@/components/ui/Button";
import { api } from "@/lib/api";

const MIN_PASSWORD_LENGTH = 8;

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

  const passwordValid = password.length >= MIN_PASSWORD_LENGTH;

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!passwordValid) {
      setError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
      return;
    }

    setLoading(true);

    try {
      await api.register({ email, password });
      setSuccess(true);
      setTimeout(() => {
        router.push("/login");
      }, 1500);
    } catch (err) {
      if (err instanceof Error) {
        if (err.message.includes("409") || err.message.toLowerCase().includes("already")) {
          setError("An account with this email already exists");
        } else {
          setError(err.message);
        }
      } else {
        setError("Registration failed");
      }
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <Container className="py-24 min-h-[60vh] flex flex-col items-center justify-center">
        <p className="text-3xl font-bold tracking-tighter">Account Created</p>
        <p className="text-neutral-500 mt-4">Redirecting to login...</p>
      </Container>
    );
  }

  return (
    <Container className="py-24">
      <div className="max-w-md mx-auto">
        <h1 className="text-5xl font-bold tracking-tighter mb-12">Register</h1>

        <form onSubmit={handleSubmit} className="space-y-8">
          <Input
            type="email"
            label="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@example.com"
            required
            error={error ? " " : undefined}
          />

          <div className="w-full">
            <label className="block text-xs font-bold tracking-widest uppercase text-neutral-500 mb-2">
              Password
            </label>
            <div className="relative">
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                required
                className={`w-full border-b py-3 bg-transparent text-black placeholder:text-neutral-400 focus:outline-none transition-colors ${
                  error
                    ? "border-red-500 animate-shake"
                    : password.length > 0
                    ? passwordValid
                      ? "border-green-500"
                      : "border-yellow-500"
                    : "border-neutral-200 focus:border-black"
                }`}
              />
              <span
                className={`absolute right-0 top-1/2 -translate-y-1/2 text-xs ${
                  passwordValid ? "text-green-500" : "text-neutral-400"
                }`}
              >
                {password.length}/{MIN_PASSWORD_LENGTH}
              </span>
            </div>
          </div>

          {error && <p className="text-sm text-red-500">{error}</p>}

          <Button type="submit" disabled={loading} className="w-full">
            {loading ? "Creating account..." : success ? "Created" : "Create Account"}
          </Button>
        </form>

        <p className="text-center mt-8 text-neutral-500">
          Already have an account?{" "}
          <Link href="/login" className="text-black underline hover:no-underline">
            Sign in
          </Link>
        </p>
      </div>
    </Container>
  );
}
