"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, type FormEvent } from "react";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardFooter, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { ROUTES } from "@/config/routes.config";

interface FieldErrors {
  name?: string;
  email?: string;
  password?: string;
  confirmPassword?: string;
}

interface RegisterResponse {
  success: boolean;
  data?: { user: unknown };
  message?: string;
  code?: string;
  details?: { fieldErrors?: FieldErrors; formErrors?: string[] };
}

export function RegisterForm() {
  const router = useRouter();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [errors, setErrors] = useState<FieldErrors>({});
  const [serverError, setServerError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setErrors({});
    setServerError(null);
    setSubmitting(true);

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

      if (!res.ok || !json.success) {
        if (json.code === "CONFLICT") {
          setErrors({ email: "An account with this email already exists." });
        } else if (json.code === "VALIDATION_ERROR") {
          setErrors(json.details?.fieldErrors ?? {});
          setServerError(json.message ?? "Please check your input.");
        } else {
          setServerError(json.message ?? "Registration failed. Please try again.");
        }
        return;
      }

      router.replace(ROUTES.dashboard);
      router.refresh();
    } catch {
      setServerError("Network error. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Card>
      <CardHeader>
        <h1 className="text-xl font-semibold tracking-tight text-foreground">
          Create your account
        </h1>
        <p className="mt-1 text-sm text-muted">
          Get started — it only takes a minute.
        </p>
      </CardHeader>
      <CardBody>
        <form className="space-y-4" onSubmit={handleSubmit} noValidate>
          {serverError ? <Alert tone="error">{serverError}</Alert> : null}
          <Input
            label="Name"
            name="name"
            autoComplete="name"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
            error={errors.name}
            placeholder="Jane Doe"
          />
          <Input
            label="Email"
            type="email"
            name="email"
            autoComplete="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            error={errors.email}
            placeholder="you@example.com"
          />
          <Input
            label="Password"
            type="password"
            name="password"
            autoComplete="new-password"
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            error={errors.password}
            hint="At least 8 characters."
            placeholder="••••••••"
          />
          <Input
            label="Confirm password"
            type="password"
            name="confirmPassword"
            autoComplete="new-password"
            required
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            error={errors.confirmPassword}
            placeholder="••••••••"
          />
          <Button type="submit" fullWidth isLoading={submitting}>
            {submitting ? "Creating account…" : "Create account"}
          </Button>
        </form>
      </CardBody>
      <CardFooter>
        <p className="text-sm text-muted w-full text-center">
          Already have an account?{" "}
          <Link
            href={ROUTES.login}
            className="text-primary hover:text-primary-hover font-medium"
          >
            Sign in
          </Link>
        </p>
      </CardFooter>
    </Card>
  );
}
