import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { SurveyForm } from "@/components/survey/survey-form";

type PageProps = {
  params: Promise<{ orgSlug: string; formSlug: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

export default async function PublicSurveyPage({
  params,
  searchParams,
}: PageProps) {
  const { orgSlug, formSlug } = await params;
  const query = await searchParams;

  const org = await prisma.organization.findUnique({
    where: { slug: orgSlug },
    select: { id: true, name: true },
  });

  if (!org) notFound();

  const template = await prisma.formTemplate.findUnique({
    where: {
      organizationId_slug: {
        organizationId: org.id,
        slug: formSlug,
      },
    },
    include: {
      fields: {
        where: { visibleOnSurvey: true },
        orderBy: { sortOrder: "asc" },
      },
    },
  });

  if (!template || !template.isActive) notFound();

  const branding = template.branding as {
    primaryColor?: string;
    logoUrl?: string;
  } | null;

  const prefill: Record<string, string> = {};
  for (const [key, val] of Object.entries(query)) {
    if (typeof val === "string") prefill[key] = val;
  }

  return (
    <div className="space-y-6">
      <div className="text-center">
        {branding?.logoUrl && (
          <img
            src={branding.logoUrl}
            alt={org.name}
            className="mx-auto mb-4 h-16 w-auto object-contain"
          />
        )}
        <h1
          className="text-2xl font-bold tracking-tight"
          style={branding?.primaryColor ? { color: branding.primaryColor } : undefined}
        >
          {template.name}
        </h1>
        <p className="mt-1 text-sm text-muted-foreground">{org.name}</p>
        {template.description && (
          <p className="mt-2 text-sm text-muted-foreground">
            {template.description}
          </p>
        )}
      </div>

      <SurveyForm
        formTemplateId={template.id}
        organizationId={org.id}
        fields={template.fields}
        branding={branding}
        prefill={prefill}
      />
    </div>
  );
}
