"use client";

import { useState, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Eye, EyeOff, Loader2, CheckCircle2 } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  validateEmail,
  validatePassword,
  clearFieldError,
} from "@/utils/form-validation";

export type RegistrationFieldErrors = Partial<
  Record<"fullName" | "email" | "password" | "confirmPassword", string>
>;

export interface RegistrationFormProps {
  onSuccess?: () => void;
  className?: string;
}

function RegistrationSuccessView({
  onSignIn,
  onBack,
  className,
}: {
  onSignIn: () => void;
  onBack: () => void;
  className?: string;
}) {
  return (
    <div className={cn("flex flex-col items-center justify-center px-2 py-6 text-center", className)}>
      <span className="immersive-chip mb-4">
        <CheckCircle2 className="size-5" aria-hidden />
      </span>
      <h3 className="font-heading text-lg font-medium tracking-tight text-[hsl(var(--foreground))]">
        You&apos;re all set
      </h3>
      <p className="mt-2 max-w-xs text-sm text-[hsl(var(--muted-foreground))]">
        Your account request has been received. We&apos;ll be in touch shortly.
      </p>
      <div className="mt-6 flex w-full max-w-xs flex-col gap-3 sm:flex-row">
        <button
          type="button"
          onClick={onSignIn}
          className="flex-1 rounded-lg bg-[hsl(var(--primary))] px-5 py-2.5 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))]"
        >
          Sign in
        </button>
        <button
          type="button"
          onClick={onBack}
          className="flex-1 rounded-lg border border-white/15 px-5 py-2.5 text-sm font-semibold text-[hsl(var(--foreground))] transition-colors hover:border-white/35"
        >
          Back to home
        </button>
      </div>
    </div>
  );
}

const FIELDS = [
  { name: "fullName", label: "Full name", type: "text", autoComplete: "name", placeholder: "Jane Smith" },
  { name: "email", label: "Email", type: "email", autoComplete: "email", placeholder: "you@company.com" },
] as const;

export function RegistrationForm({ onSuccess, className }: RegistrationFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<RegistrationFieldErrors>({});
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const handleClearError = (field: keyof RegistrationFieldErrors) => {
    setFieldErrors((prev) => clearFieldError(prev, field));
  };

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setFieldErrors({});

    const form = e.currentTarget;
    const fullName = String(form.fullName?.value ?? "").trim();
    const email = String(form.email?.value ?? "").trim();
    const password = String(form.password?.value ?? "");
    const confirmPassword = String(form.confirmPassword?.value ?? "");

    const errors: RegistrationFieldErrors = {};

    if (!fullName) errors.fullName = "Full name is required.";
    else if (fullName.length < 2) errors.fullName = "Name must be at least 2 characters.";

    const emailError = validateEmail(email);
    if (emailError) errors.email = emailError;

    const passwordError = validatePassword(password, "Password", 8);
    if (passwordError) errors.password = passwordError;

    if (password !== confirmPassword) {
      errors.confirmPassword = "Passwords do not match.";
    } else if (!confirmPassword) {
      errors.confirmPassword = "Please confirm your password.";
    }

    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }

    setLoading(true);
    try {
      await new Promise((r) => setTimeout(r, 800));
      setSuccess(true);
      onSuccess?.();
    } catch {
      setFieldErrors({ email: "Registration failed. Please try again." });
    } finally {
      setLoading(false);
    }
  }

  if (success) {
    return (
      <RegistrationSuccessView
        className={className}
        onSignIn={() => router.push("/login")}
        onBack={() => (onSuccess ? onSuccess() : router.push("/"))}
      />
    );
  }

  return (
    <form onSubmit={handleSubmit} className={cn("flex flex-col gap-5", className)} noValidate>
      {FIELDS.map((field) => (
        <div key={field.name} className="flex flex-col gap-2">
          <label htmlFor={`reg-${field.name}`} className="immersive-label">
            {field.label}
          </label>
          <input
            id={`reg-${field.name}`}
            name={field.name}
            type={field.type}
            placeholder={field.placeholder}
            autoComplete={field.autoComplete}
            aria-invalid={!!fieldErrors[field.name]}
            onFocus={() => handleClearError(field.name)}
            className={cn(
              "w-full border-b border-white/10 bg-transparent pb-2.5 text-base text-[hsl(var(--foreground))] outline-none transition-colors placeholder:text-[hsl(var(--muted-foreground))]/60 focus:border-[hsl(var(--primary))]",
              fieldErrors[field.name] && "border-[hsl(var(--destructive))]"
            )}
          />
          {fieldErrors[field.name] && (
            <p className="text-xs text-[hsl(var(--destructive))]">{fieldErrors[field.name]}</p>
          )}
        </div>
      ))}

      <div className="flex flex-col gap-2">
        <label htmlFor="reg-password" className="immersive-label">
          Password
        </label>
        <div className="relative">
          <input
            id="reg-password"
            name="password"
            type={showPassword ? "text" : "password"}
            placeholder="At least 8 characters"
            autoComplete="new-password"
            aria-invalid={!!fieldErrors.password}
            onFocus={() => handleClearError("password")}
            className={cn(
              "w-full border-b border-white/10 bg-transparent pb-2.5 pr-9 text-base text-[hsl(var(--foreground))] outline-none transition-colors placeholder:text-[hsl(var(--muted-foreground))]/60 focus:border-[hsl(var(--primary))]",
              fieldErrors.password && "border-[hsl(var(--destructive))]"
            )}
          />
          <button
            type="button"
            tabIndex={-1}
            onClick={() => setShowPassword((p) => !p)}
            aria-label={showPassword ? "Hide password" : "Show password"}
            className="absolute right-0 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center text-[hsl(var(--muted-foreground))] transition-colors hover:text-[hsl(var(--foreground))]"
          >
            {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
          </button>
        </div>
        {fieldErrors.password && (
          <p className="text-xs text-[hsl(var(--destructive))]">{fieldErrors.password}</p>
        )}
      </div>

      <div className="flex flex-col gap-2">
        <label htmlFor="reg-confirmPassword" className="immersive-label">
          Confirm password
        </label>
        <div className="relative">
          <input
            id="reg-confirmPassword"
            name="confirmPassword"
            type={showConfirmPassword ? "text" : "password"}
            placeholder="Repeat password"
            autoComplete="new-password"
            aria-invalid={!!fieldErrors.confirmPassword}
            onFocus={() => handleClearError("confirmPassword")}
            className={cn(
              "w-full border-b border-white/10 bg-transparent pb-2.5 pr-9 text-base text-[hsl(var(--foreground))] outline-none transition-colors placeholder:text-[hsl(var(--muted-foreground))]/60 focus:border-[hsl(var(--primary))]",
              fieldErrors.confirmPassword && "border-[hsl(var(--destructive))]"
            )}
          />
          <button
            type="button"
            tabIndex={-1}
            onClick={() => setShowConfirmPassword((p) => !p)}
            aria-label={showConfirmPassword ? "Hide password" : "Show password"}
            className="absolute right-0 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center text-[hsl(var(--muted-foreground))] transition-colors hover:text-[hsl(var(--foreground))]"
          >
            {showConfirmPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
          </button>
        </div>
        {fieldErrors.confirmPassword && (
          <p className="text-xs text-[hsl(var(--destructive))]">{fieldErrors.confirmPassword}</p>
        )}
      </div>

      <button
        type="submit"
        disabled={loading}
        className="group mt-2 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-[hsl(var(--primary))] px-6 py-3 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))] disabled:opacity-60"
      >
        {loading ? (
          <>
            <Loader2 className="size-4 animate-spin" />
            Creating account…
          </>
        ) : (
          "Create account"
        )}
      </button>

      <p className="text-center text-xs text-[hsl(var(--muted-foreground))]">
        Already have an account?{" "}
        <button
          type="button"
          className="font-semibold text-[hsl(var(--primary))] hover:underline"
          onClick={() => router.push("/login")}
        >
          Sign in
        </button>
      </p>
    </form>
  );
}
