"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateImportReviewPage = generateImportReviewPage;
const import_review_page_result_stage_generator_1 = require("./import-review-page-result-stage.generator");
const import_review_page_review_stage_generator_1 = require("./import-review-page-review-stage.generator");
const import_review_page_upload_stage_generator_1 = require("./import-review-page-upload-stage.generator");
/**
 * Generator function that generates the Import Review admin page.
 */
function generateImportReviewPage({ context }) {
    const models = [...context.models.values()].sort((a, b) => a.userFriendlyName.localeCompare(b.userFriendlyName));
    const modelSchemaMapEntries = models
        .map((model) => `  ${model._conjugated.camelCasePlural}: '${model.databaseSchema}',`)
        .join('\n');
    const modelLabelMapEntries = models
        .map((model) => `  ${model._conjugated.camelCasePlural}: '${model.userFriendlyName.replaceAll("'", "\\'")}',`)
        .join('\n');
    const modelFieldOrderEntries = models
        .map((model) => {
        const fields = Array.from(model.fields.values())
            .map((field) => `'${field.name}'`)
            .join(', ');
        return `  ${model._conjugated.camelCasePlural}: [${fields}],`;
    })
        .join('\n');
    const schemaOrderEntries = [...new Set(models.map((model) => model.databaseSchema))]
        .sort((a, b) => a.localeCompare(b))
        .map((schema) => `'${schema}'`)
        .join(', ');
    return `
import { AdminSidebarNavContent } from '@admin/admin-sidebar-nav-content'

import type { ColumnDef } from '@tanstack/react-table'
import { useEffect, useMemo, useState } from 'react'
import { AlertTriangleIcon, ListTree, MinusIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react'

import type {
  ImportExecutionSummary,
  ImportPreviewItem,
  ImportPreviewModelSummary,
  ImportPreviewResponse,
  SelectedDeltaIndicesByModel,
} from '@hooks/use-import-review'
import { useImportReview } from '@hooks/use-import-review'
import {
  Alert,
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDescription,
  Badge,
  Button,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Checkbox,
  DataGrid,
  Input,
  Label,
  SidebarTab,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
  cn,
  useDataGrid,
} from '@postxl/ui-components'

const MODEL_SCHEMA_MAP: Record<string, string> = {
${modelSchemaMapEntries}
}

const MODEL_LABEL_MAP: Record<string, string> = {
${modelLabelMapEntries}
}

const MODEL_FIELD_ORDER: Record<string, string[]> = {
${modelFieldOrderEntries}
}

const SCHEMA_ORDER: string[] = [${schemaOrderEntries}]

const TYPE_ORDER: ImportPreviewItem['type'][] = ['errors', 'delete', 'update', 'create', 'unchanged']

const TYPE_BADGE_CLASSES: Record<ImportPreviewItem['type'], string> = {
  create: 'text-green-700 border-green-300 dark:text-green-400 dark:border-green-700',
  update: 'text-blue-700 border-blue-300 dark:text-blue-400 dark:border-blue-700',
  delete: 'text-red-700 border-red-300 dark:text-red-400 dark:border-red-700',
  unchanged: 'text-muted-foreground border-border',
  errors: 'text-red-700 border-red-300 dark:text-red-400 dark:border-red-700',
}

const EXECUTABLE_TYPES = new Set<ImportPreviewItem['type']>(['create', 'update', 'delete'])

export default function ImportReviewPage() {
  const { stage, preview, executionResult, error, isLoading, uploadAndPreview, execute, reset } = useImportReview()

  const showAdminSidebar = stage === 'upload' || stage === 'previewing' || stage === 'result'

  return (
    <>
      {showAdminSidebar && (<SidebarTab
        side="left"
        id="admin-navigation"
        icon={ListTree}
        label="Navigation"
      >
        <AdminSidebarNavContent />
      </SidebarTab>)}

      <div className="p-4 overflow-auto gap-4">
        <div className="mx-auto flex w-full max-w-[1400px] flex-col gap-4">
          <PageHeader stage={stage} />

          {error && (
            <Alert variant="destructive">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {(stage === 'upload' || stage === 'previewing') && (
            <UploadStage isLoading={isLoading} onUpload={uploadAndPreview} />
          )}

          {stage === 'review' && preview && (
            <ReviewStage preview={preview} isLoading={isLoading} onExecute={execute} onReset={reset} />
          )}

          {stage === 'executing' && (
            <Card>
              <CardContent className="py-8 text-center">
                <p className="text-lg font-medium">Executing selected changes...</p>
                <p className="mt-2 text-sm text-muted-foreground">Applying selected rows to the database.</p>
              </CardContent>
            </Card>
          )}

          {stage === 'result' && executionResult && <ResultStage result={executionResult} onReset={reset} />}
        </div>
      </div>
    </>
  )
}

function PageHeader({ stage }: Readonly<{ stage: 'upload' | 'previewing' | 'review' | 'executing' | 'result' }>) {
  const currentStep = stage === 'upload' || stage === 'previewing' ? 1 : stage === 'review' || stage === 'executing' ? 2 : 3

  return (
    <div className="space-y-3">
      <h1 className="text-3xl font-bold">Import Review</h1>
      <p className="text-sm text-muted-foreground">
        Upload an Excel file, review and select changes, then execute a controlled import.
      </p>
      <div className="grid grid-cols-3 gap-2">
        <StepChip label="1. Upload" active={currentStep === 1} done={currentStep > 1} />
        <StepChip label="2. Preview & Select" active={currentStep === 2} done={currentStep > 2} />
        <StepChip label="3. Results" active={currentStep === 3} done={false} />
      </div>
    </div>
  )
}

function StepChip({ label, active, done }: Readonly<{ label: string; active: boolean; done: boolean }>) {
  const stateClass = done
    ? 'border-green-300 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-950/40 dark:text-green-300'
    : active
      ? 'border-blue-300 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-950/40 dark:text-blue-300'
      : 'border-border bg-background text-muted-foreground'

  return <div className={cn('rounded border px-3 py-2 text-sm font-medium', stateClass)}>{label}</div>
}

${(0, import_review_page_upload_stage_generator_1.generateImportReviewUploadStage)()}

${(0, import_review_page_review_stage_generator_1.generateImportReviewReviewStage)()}

${(0, import_review_page_result_stage_generator_1.generateImportReviewResultStage)()}
`;
}
//# sourceMappingURL=import-review-page.generator.js.map