import { ContentPageType, OrganizationDocumentType, OverallScoreMethod, UserRole } from "@prisma/client";
import { PageShell } from "@/components/app/page-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { requireAdminUser } from "@/lib/auth/admin";
import { getScoringConfig } from "@/lib/scoring-config";
import { prisma } from "@/lib/prisma";

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

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

const statusMessages: Record<string, string> = {
  role_updated: "Rol de usuario actualizado.",
  content_created: "Contenido creado correctamente.",
  content_updated: "Contenido actualizado correctamente.",
  scoring_updated: "Configuracion de scoring actualizada.",
  admin_error: "No se pudo completar la operacion de admin.",
};

export default async function AdminPage({ searchParams }: AdminPageProps) {
  await requireAdminUser();

  const params = await searchParams;
  const status = getParam(params, "status");
  const statusMessage = status ? statusMessages[status] : null;

  const [users, contentPages, modules, scoringConfig] = await Promise.all([
    prisma.user.findMany({
      orderBy: { createdAt: "desc" },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        emailVerifiedAt: true,
        createdAt: true,
        organization: {
          select: {
            id: true,
            name: true,
            onboardingCompletedAt: true,
            documents: {
              where: { type: OrganizationDocumentType.ACTA_CONSTITUTIVA },
              select: { id: true },
              take: 1,
            },
          },
        },
      },
    }),
    prisma.contentPage.findMany({
      orderBy: [{ type: "asc" }, { sortOrder: "asc" }, { createdAt: "asc" }],
      select: {
        id: true,
        type: true,
        slug: true,
        title: true,
        content: true,
        sortOrder: true,
        isPublished: true,
      },
    }),
    prisma.diagnosticModule.findMany({
      orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
      select: {
        key: true,
        name: true,
      },
    }),
    getScoringConfig(),
  ]);

  return (
    <PageShell title="Admin Portal" description="Gestiona usuarios, contenidos y configuracion de scoring.">
      {statusMessage ? (
        <Card>
          <CardContent className="py-4">
            <p className="text-sm font-semibold text-[#35527c]">{statusMessage}</p>
          </CardContent>
        </Card>
      ) : null}

      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Configuracion de scoring</h2>
        </CardHeader>
        <CardContent>
          <form action="/api/admin/scoring" method="post" className="space-y-4">
            <div className="grid gap-4 md:grid-cols-2">
              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Umbral de modulo bajo (%)
                <input
                  type="number"
                  name="lowScoreThreshold"
                  min={0}
                  max={100}
                  defaultValue={scoringConfig.lowScoreThreshold}
                  className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm"
                />
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Metodo de score global
                <select
                  name="overallScoreMethod"
                  defaultValue={scoringConfig.overallScoreMethod}
                  className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm"
                >
                  <option value={OverallScoreMethod.EQUAL_ALL_MODULES}>Promedio igual entre todos los modulos</option>
                  <option value={OverallScoreMethod.EQUAL_ANSWERED_MODULES}>Promedio igual entre modulos respondidos</option>
                  <option value={OverallScoreMethod.WEIGHTED_ANSWERED_MODULES}>Promedio ponderado por modulo (respondidos)</option>
                </select>
              </label>
            </div>

            <div className="space-y-2">
              <p className="text-sm font-semibold text-[#33415c]">Pesos por modulo (solo aplica en metodo ponderado)</p>
              <div className="grid gap-3 md:grid-cols-2">
                {modules.map((module) => (
                  <label key={module.key} className="space-y-1 text-sm font-medium text-[#52617b]">
                    {module.name}
                    <input
                      type="number"
                      name={`weight:${module.key}`}
                      min={0.1}
                      step={0.1}
                      defaultValue={scoringConfig.moduleWeights[module.key] ?? 1}
                      className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm"
                    />
                  </label>
                ))}
              </div>
            </div>

            <Button type="submit">Guardar scoring</Button>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Usuarios</h2>
        </CardHeader>
        <CardContent className="space-y-3">
          {users.map((user) => {
            const completedOnboarding = Boolean(user.organization?.onboardingCompletedAt && user.organization.documents.length > 0);

            return (
            <div key={user.id} className="rounded-xl border border-[#e1e8f4] p-3">
              <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
                <div>
                  <p className="text-sm font-semibold text-[#273750]">{user.name ?? "Sin nombre"}</p>
                  <p className="text-xs text-[#5f6d86]">{user.email}</p>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant={user.emailVerifiedAt ? "success" : "warning"}>{user.emailVerifiedAt ? "Verificado" : "No verificado"}</Badge>
                  <Badge variant={completedOnboarding ? "success" : "neutral"}>
                    {completedOnboarding ? "Onboarded" : "Sin onboarding"}
                  </Badge>
                </div>
              </div>

              <form action="/api/admin/users/role" method="post" className="flex flex-wrap items-end gap-2">
                <input type="hidden" name="userId" value={user.id} />
                <label className="text-sm font-semibold text-[#33415c]">
                  Rol
                  <select name="role" defaultValue={user.role} className="ml-2 h-9 rounded-lg border border-[#cfd8e6] px-2 text-sm">
                    <option value={UserRole.USER}>USER</option>
                    <option value={UserRole.ADMIN}>ADMIN</option>
                  </select>
                </label>
                <Button type="submit" size="sm" variant="secondary">
                  Actualizar rol
                </Button>
              </form>
            </div>
            );
          })}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Crear contenido (Manual / FAQ)</h2>
        </CardHeader>
        <CardContent>
          <form action="/api/admin/content/create" method="post" className="grid gap-3 md:grid-cols-2">
            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Tipo
              <select name="type" className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" defaultValue={ContentPageType.FAQ}>
                <option value={ContentPageType.FAQ}>FAQ</option>
                <option value={ContentPageType.MANUAL}>MANUAL</option>
              </select>
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Slug
              <input name="slug" required className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" placeholder="faq-nueva-politica" />
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c] md:col-span-2">
              Titulo
              <input name="title" required className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" placeholder="Nueva entrada" />
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c] md:col-span-2">
              Contenido
              <textarea name="content" required rows={4} className="w-full rounded-lg border border-[#cfd8e6] px-3 py-2 text-sm" />
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Orden
              <input type="number" name="sortOrder" defaultValue={1} className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" />
            </label>

            <label className="flex items-center gap-2 text-sm font-semibold text-[#33415c]">
              <input type="checkbox" name="isPublished" defaultChecked className="h-4 w-4" />
              Publicado
            </label>

            <div className="md:col-span-2">
              <Button type="submit">Crear contenido</Button>
            </div>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Contenido existente</h2>
        </CardHeader>
        <CardContent className="space-y-3">
          {contentPages.map((page) => (
            <form key={page.id} action="/api/admin/content/update" method="post" className="space-y-2 rounded-xl border border-[#e1e8f4] p-3">
              <input type="hidden" name="id" value={page.id} />

              <div className="grid gap-3 md:grid-cols-2">
                <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                  Tipo
                  <select name="type" defaultValue={page.type} className="h-9 w-full rounded-lg border border-[#cfd8e6] px-2 text-sm">
                    <option value={ContentPageType.FAQ}>FAQ</option>
                    <option value={ContentPageType.MANUAL}>MANUAL</option>
                  </select>
                </label>

                <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                  Slug
                  <input name="slug" defaultValue={page.slug} className="h-9 w-full rounded-lg border border-[#cfd8e6] px-2 text-sm" />
                </label>

                <label className="space-y-1 text-sm font-semibold text-[#33415c] md:col-span-2">
                  Titulo
                  <input name="title" defaultValue={page.title} className="h-9 w-full rounded-lg border border-[#cfd8e6] px-2 text-sm" />
                </label>

                <label className="space-y-1 text-sm font-semibold text-[#33415c] md:col-span-2">
                  Contenido
                  <textarea name="content" defaultValue={page.content} rows={3} className="w-full rounded-lg border border-[#cfd8e6] px-2 py-2 text-sm" />
                </label>

                <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                  Orden
                  <input type="number" name="sortOrder" defaultValue={page.sortOrder} className="h-9 w-full rounded-lg border border-[#cfd8e6] px-2 text-sm" />
                </label>

                <label className="flex items-center gap-2 text-sm font-semibold text-[#33415c]">
                  <input type="checkbox" name="isPublished" defaultChecked={page.isPublished} className="h-4 w-4" />
                  Publicado
                </label>
              </div>

              <Button type="submit" size="sm" variant="secondary">
                Guardar cambios
              </Button>
            </form>
          ))}
        </CardContent>
      </Card>
    </PageShell>
  );
}
