import { redirect } from "next/navigation";
import { OrganizationDocumentType } from "@prisma/client";
import { OnboardingWizard } from "@/components/app/onboarding-wizard";
import { PageShell } from "@/components/app/page-shell";
import { requireUser } from "@/lib/auth/user";
import { prisma } from "@/lib/prisma";

export default async function OnboardingPage() {
  const user = await requireUser();

  let existingOrganization: {
    name: string;
    tradeName: string | null;
    rfc: string | null;
    legalRepresentative: string | null;
    incorporationDate: string | null;
    deedNumber: string | null;
    notaryName: string | null;
    fiscalAddress: string | null;
    businessPurpose: string | null;
    industry: string | null;
    operatingState: string | null;
    municipality: string | null;
    companySize: string | null;
    yearsOfOperation: string | null;
    annualRevenueRange: string | null;
    hasGovernmentContracts: boolean | null;
    country: string | null;
    primaryObjective: string | null;
    actaUploadedAt: Date | null;
    onboardingCompletedAt: Date | null;
  } | null = null;
  let hasActaDocument = false;

  try {
    existingOrganization = await prisma.organization.findUnique({
      where: { userId: user.id },
      select: {
        name: true,
        tradeName: true,
        rfc: true,
        legalRepresentative: true,
        incorporationDate: true,
        deedNumber: true,
        notaryName: true,
        fiscalAddress: true,
        businessPurpose: true,
        industry: true,
        operatingState: true,
        municipality: true,
        companySize: true,
        yearsOfOperation: true,
        annualRevenueRange: true,
        hasGovernmentContracts: true,
        country: true,
        primaryObjective: true,
        actaUploadedAt: true,
        onboardingCompletedAt: true,
      },
    });

    const existingActa = await prisma.organizationDocument.findUnique({
      where: {
        userId_type: {
          userId: user.id,
          type: OrganizationDocumentType.ACTA_CONSTITUTIVA,
        },
      },
      select: { id: true },
    });

    hasActaDocument = Boolean(existingActa);
  } catch {
    // Backward compatibility for older schema before onboarding v2 migration.
    const legacyOrganization = await prisma.organization.findUnique({
      where: { userId: user.id },
      select: {
        name: true,
        industry: true,
        companySize: true,
        country: true,
        primaryObjective: true,
      },
    });

    existingOrganization = legacyOrganization
      ? {
          name: legacyOrganization.name,
          tradeName: null,
          rfc: null,
          legalRepresentative: null,
          incorporationDate: null,
          deedNumber: null,
          notaryName: null,
          fiscalAddress: null,
          businessPurpose: null,
          industry: legacyOrganization.industry,
          operatingState: null,
          municipality: null,
          companySize: legacyOrganization.companySize,
          yearsOfOperation: null,
          annualRevenueRange: null,
          hasGovernmentContracts: null,
          country: legacyOrganization.country,
          primaryObjective: legacyOrganization.primaryObjective,
          actaUploadedAt: null,
          onboardingCompletedAt: null,
        }
      : null;
  }

  if (existingOrganization?.onboardingCompletedAt) {
    redirect("/diagnostic");
  }

  return (
    <PageShell
      title="Onboarding Empresarial"
      description="Paso 1: carga tu Acta constitutiva en PDF para extraer datos base. Luego confirma y completa el perfil."
    >
      <OnboardingWizard
        initialValues={{
          name: existingOrganization?.name ?? "",
          tradeName: existingOrganization?.tradeName ?? "",
          rfc: existingOrganization?.rfc ?? "",
          legalRepresentative: existingOrganization?.legalRepresentative ?? "",
          incorporationDate: existingOrganization?.incorporationDate ?? "",
          deedNumber: existingOrganization?.deedNumber ?? "",
          notaryName: existingOrganization?.notaryName ?? "",
          fiscalAddress: existingOrganization?.fiscalAddress ?? "",
          businessPurpose: existingOrganization?.businessPurpose ?? "",
          industry: existingOrganization?.industry ?? "",
          operatingState: existingOrganization?.operatingState ?? "",
          municipality: existingOrganization?.municipality ?? "",
          companySize: existingOrganization?.companySize ?? "",
          yearsOfOperation: existingOrganization?.yearsOfOperation ?? "",
          annualRevenueRange: existingOrganization?.annualRevenueRange ?? "",
          hasGovernmentContracts:
            existingOrganization?.hasGovernmentContracts === null || existingOrganization?.hasGovernmentContracts === undefined
              ? ""
              : existingOrganization.hasGovernmentContracts
                ? "yes"
                : "no",
          country: existingOrganization?.country ?? "",
          primaryObjective: existingOrganization?.primaryObjective ?? "",
        }}
        hasActaDocument={hasActaDocument}
        actaUploadedAt={existingOrganization?.actaUploadedAt?.toISOString() ?? null}
      />
    </PageShell>
  );
}
