"use client";

import { useState, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Eye, EyeOff, Loader2, User, Mail, Lock, CheckCircle2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
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 py-8 px-2 text-center", className)}>
      <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-orange/10 text-orange">
        <CheckCircle2 className="h-6 w-6" />
      </div>
      <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">You're all set</h3>
      <p className="text-sm text-gray-600 dark:text-gray-400 mb-6 max-w-xs">
        Your account request has been received. We'll be in touch shortly.
      </p>
      <div className="flex flex-col sm:flex-row gap-3 w-full max-w-xs">
        <Button
          type="button"
          className="flex-1 bg-orange hover:bg-orange-dark text-white"
          onClick={onSignIn}
        >
          Sign in
        </Button>
        <Button type="button" variant="outline" className="flex-1" onClick={onBack}>
          Back to home
        </Button>
      </div>
    </div>
  );
}

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("space-y-4", className)}
      noValidate
    >
      <div className="space-y-1.5">
        <Label htmlFor="reg-fullName" className="text-sm font-medium text-gray-700 dark:text-gray-300">
          Full name
        </Label>
        <div className="relative">
          <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
          <Input
            id="reg-fullName"
            name="fullName"
            type="text"
            placeholder="Jane Smith"
            autoComplete="name"
            className="pl-9 h-10 rounded-lg"
            aria-invalid={!!fieldErrors.fullName}
            onFocus={() => handleClearError("fullName")}
          />
        </div>
        {fieldErrors.fullName && (
          <p className="text-xs text-red-600 dark:text-red-400">{fieldErrors.fullName}</p>
        )}
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="reg-email" className="text-sm font-medium text-gray-700 dark:text-gray-300">
          Email
        </Label>
        <div className="relative">
          <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
          <Input
            id="reg-email"
            name="email"
            type="email"
            placeholder="you@company.com"
            autoComplete="email"
            className="pl-9 h-10 rounded-lg"
            aria-invalid={!!fieldErrors.email}
            onFocus={() => handleClearError("email")}
          />
        </div>
        {fieldErrors.email && (
          <p className="text-xs text-red-600 dark:text-red-400">{fieldErrors.email}</p>
        )}
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="reg-password" className="text-sm font-medium text-gray-700 dark:text-gray-300">
          Password
        </Label>
        <div className="relative">
          <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
          <Input
            id="reg-password"
            name="password"
            type={showPassword ? "text" : "password"}
            placeholder="At least 8 characters"
            autoComplete="new-password"
            className="pl-9 pr-10 h-10 rounded-lg"
            aria-invalid={!!fieldErrors.password}
            onFocus={() => handleClearError("password")}
          />
          <button
            type="button"
            tabIndex={-1}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
            onClick={() => setShowPassword((p) => !p)}
            aria-label={showPassword ? "Hide password" : "Show password"}
          >
            {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
          </button>
        </div>
        {fieldErrors.password && (
          <p className="text-xs text-red-600 dark:text-red-400">{fieldErrors.password}</p>
        )}
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="reg-confirmPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
          Confirm password
        </Label>
        <div className="relative">
          <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
          <Input
            id="reg-confirmPassword"
            name="confirmPassword"
            type={showConfirmPassword ? "text" : "password"}
            placeholder="Repeat password"
            autoComplete="new-password"
            className="pl-9 pr-10 h-10 rounded-lg"
            aria-invalid={!!fieldErrors.confirmPassword}
            onFocus={() => handleClearError("confirmPassword")}
          />
          <button
            type="button"
            tabIndex={-1}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
            onClick={() => setShowConfirmPassword((p) => !p)}
            aria-label={showConfirmPassword ? "Hide password" : "Show password"}
          >
            {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
          </button>
        </div>
        {fieldErrors.confirmPassword && (
          <p className="text-xs text-red-600 dark:text-red-400">{fieldErrors.confirmPassword}</p>
        )}
      </div>

      <Button
        type="submit"
        disabled={loading}
        className="w-full h-10 rounded-lg bg-orange hover:bg-orange-dark text-white font-medium"
      >
        {loading ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" />
            Creating account…
          </>
        ) : (
          "Create account"
        )}
      </Button>

      <p className="text-center text-xs text-gray-500 dark:text-gray-400">
        Already have an account?{" "}
        <button
          type="button"
          className="font-medium text-orange hover:underline"
          onClick={() => router.push("/login")}
        >
          Sign in
        </button>
      </p>
    </form>
  );
}
