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 { getCurrentUser } from "@/lib/auth/user";

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

const loginErrorMap: Record<string, string> = {
  auth_required: "Debes iniciar sesion para acceder a esta seccion.",
  invalid_credentials: "Credenciales invalidas. Verifica correo y contrasena.",
  server_error: "No fue posible iniciar sesion. 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 LoginPage({ searchParams }: LoginPageProps) {
  const currentUser = await getCurrentUser();

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

  const params = await searchParams;
  const errorCode = getParam(params, "error");
  const errorMessage = errorCode ? loginErrorMap[errorCode] : null;
  const logoutMessage = getParam(params, "logged_out") === "1" ? "Sesion cerrada correctamente." : null;

  return (
    <PageShell title="Iniciar Sesion" description="Accede para continuar tu diagnostico y revisar tus resultados.">
      <Card className="mx-auto w-full max-w-xl">
        <CardHeader>
          <h2 className="text-xl font-semibold text-[#1f2a40]">Bienvenido de nuevo</h2>
          <p className="text-sm text-[#67738c]">Ingresa tus credenciales para continuar.</p>
        </CardHeader>
        <CardContent className="space-y-4">
          {logoutMessage ? (
            <p className="rounded-lg border border-[#ccead8] bg-[#ebf8f0] px-3 py-2 text-sm text-[#206546]">{logoutMessage}</p>
          ) : null}
          {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/login" method="post" className="space-y-4">
            <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="current-password"
                required
              />
            </div>
            <Button className="w-full" type="submit">
              Ingresar
            </Button>
          </form>

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