import Link from "next/link";
import { redirect } from "next/navigation";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Stepper } from "@/components/ui/stepper";
import { getCurrentUser } from "@/lib/auth/user";

type RegisterPageProps = {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

const registerErrorMap: Record<string, string> = {
  invalid_input: "Completa todos los campos y usa una contrasena de al menos 8 caracteres.",
  email_in_use: "Ese correo ya esta registrado. Inicia sesion o usa otro correo.",
  server_error: "No fue posible completar el registro. Intenta nuevamente.",
};

function getParam(params: Record<string, string | string[] | undefined>, key: string) {
  const value = params[key];
  return Array.isArray(value) ? value[0] : value;
}

export default async function RegisterPage({ searchParams }: RegisterPageProps) {
  const currentUser = await getCurrentUser();

  if (currentUser) {
    redirect("/dashboard");
  }

  const params = await searchParams;
  const errorCode = getParam(params, "error");
  const errorMessage = errorCode ? registerErrorMap[errorCode] : null;

  return (
    <PageShell
      title="Crear Cuenta"
      description="Comienza el diagnostico empresarial con acceso seguro y verificacion por correo."
    >
      <Stepper steps={["Cuenta", "Verificacion", "Onboarding", "Diagnostico"]} currentStep={1} />

      <Card className="mx-auto w-full max-w-xl">
        <CardHeader>
          <h2 className="text-xl font-semibold text-[#1f2a40]">Registro</h2>
          <p className="text-sm text-[#67738c]">Ingresa tus datos para crear tu cuenta.</p>
        </CardHeader>
        <CardContent className="space-y-4">
          {errorMessage ? (
            <p className="rounded-lg border border-[#f6d0d0] bg-[#fff3f3] px-3 py-2 text-sm text-[#9d3030]">{errorMessage}</p>
          ) : null}

          <form action="/api/auth/register" method="post" className="space-y-4">
            <div>
              <Label htmlFor="name">Nombre completo</Label>
              <Input id="name" name="name" placeholder="Ana Torres" autoComplete="name" required />
            </div>
            <div>
              <Label htmlFor="email">Correo</Label>
              <Input id="email" name="email" type="email" placeholder="ana@empresa.com" autoComplete="email" required />
            </div>
            <div>
              <Label htmlFor="password">Contrasena</Label>
              <Input
                id="password"
                name="password"
                type="password"
                placeholder="********"
                autoComplete="new-password"
                minLength={8}
                required
              />
            </div>
            <Button className="w-full" type="submit">
              Crear cuenta
            </Button>
          </form>

          <p className="text-center text-sm text-[#66738b]">
            Ya tienes cuenta?{" "}
            <Link href="/login" className="font-semibold text-[#0f2a5f]">
              Inicia sesion
            </Link>
          </p>
        </CardContent>
      </Card>
    </PageShell>
  );
}
