import { requireSession } from "@/lib/session";
import { prisma } from "@/lib/prisma";
import {
  changePasswordAction,
  updateProfileAction,
} from "@/server/actions/auth";
import Link from "next/link";

export default async function ConfigPage({
  searchParams,
}: {
  searchParams: Promise<{ ok?: string; error?: string }>;
}) {
  const session = await requireSession();
  const sp = await searchParams;
  const user = await prisma.user.findUnique({
    where: { email: session.user.email! },
  });

  return (
    <div className="mx-auto max-w-lg">
      <h1 className="text-3xl font-semibold">Mi cuenta</h1>
      {sp.ok && (
        <p className="mt-2 text-sm text-[var(--lime)]">Guardado.</p>
      )}
      {sp.error && <p className="mt-2 text-sm text-red-300">{sp.error}</p>}

      <form action={updateProfileAction} className="card mt-6 space-y-3">
        <input type="hidden" name="email" value={user?.email || ""} />
        <div>
          <label className="label">Nombre</label>
          <input className="input" name="name" defaultValue={user?.name || ""} />
        </div>
        <div>
          <label className="label">Ciudad</label>
          <input className="input" name="city" defaultValue={user?.city || ""} />
        </div>
        <div>
          <label className="label">Telefono</label>
          <input className="input" name="phone" defaultValue={user?.phone || ""} />
        </div>
        <p className="text-xs text-white/40">
          Email: {user?.email} · Rol: {user?.role} · Verificado:{" "}
          {user?.isVerified ? "si" : "no"}
        </p>
        <button className="btn-primary" type="submit">
          Guardar perfil
        </button>
      </form>

      <form action={changePasswordAction} className="card mt-4 space-y-3">
        <h2 className="font-semibold">Cambiar password</h2>
        <input type="hidden" name="email" value={user?.email || ""} />
        <input className="input" name="current" type="password" placeholder="Actual" required />
        <input className="input" name="next" type="password" placeholder="Nuevo" required />
        <button className="btn-ghost" type="submit">
          Actualizar password
        </button>
      </form>

      <div className="mt-4 flex gap-3">
        <Link href="/dashboard" className="btn-ghost">
          Dashboard
        </Link>
        <Link href="/solicitudes" className="btn-ghost">
          Solicitudes
        </Link>
      </div>
    </div>
  );
}
