"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateModelAdminPage = generateModelAdminPage;
const Generator = __importStar(require("@postxl/generator"));
/**
 * Generator function that generates the Admin page for a model
 */
function generateModelAdminPage({ model, context, }) {
    const imports = Generator.ImportGenerator
        //
        .from(model.admin.page.pageComponent.location)
        .add(model.table.component)
        .add(context.admin.components.sidebar)
        .add(context.admin.components.auditLogSidebar)
        .add(model.itemsHook)
        .addImport({
        from: Generator.toPackageName('react'),
        items: [
            Generator.toFunctionName('useState'),
            Generator.toFunctionName('useCallback'),
            Generator.toFunctionName('useMemo'),
        ],
    });
    const relatedModels = [];
    for (const relatedModelName of model.relatedModelNames) {
        const relatedModel = context.models.get(relatedModelName);
        imports.add(relatedModel.itemsHook);
        relatedModels.push({
            model: relatedModel,
            mapName: relatedModel.internalPluralName,
            mapDefinition: `const {${relatedModel.itemsHook.map.name}: ${relatedModel.internalPluralName}} = ${relatedModel.itemsHook.name}()`,
        });
    }
    let createModalHook = '';
    let createModal = '';
    if (!model.isReadonly) {
        imports
            //
            .addType(model.types)
            .addType(model.types.id)
            .addImport({ from: Generator.toPackageName('sonner'), items: [Generator.toFunctionName('toast')] })
            .addImport({ from: model.forms.createModal.location, items: [model.forms.createModal.name] });
        // In case the the model does not provide any explicit label field, we generally use the id field as fallback.
        // However, in case of creating a new item, we do not have an Id yet and hence cannot show it in success and error messages.
        const hasLabelField = model.labelField.name !== model.idField.name;
        const variableName = hasLabelField ? `created${model.name}` : '_';
        const label = hasLabelField ? ` "\${${variableName}.${model.labelField.name}}"` : '';
        createModalHook = ` const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)`;
        createModal = `
    <${model.forms.createModal.name}
        open={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSuccess={(${variableName}) => {
          toast.success(\`${model.userFriendlyName}${label} created successfully!\`)
          setIsCreateModalOpen(false)
        }}
        onError={(${variableName}, error) => {
          toast.error(\`Error creating ${model.userFriendlyName}${label}: \${String(error)}\`)
        }}
      />`;
    }
    return `
${imports.generate()}

type CellSelection = {
  rowIndex: number
  columnId: string
}

export default function ${model.admin.page.pageComponent.name}() {
  ${createModalHook}

  // Track the currently focused cell for audit log filtering
  const [focusedCell, setFocusedCell] = useState<CellSelection | null>(null)

  // Track selected row IDs from checkbox selection
  const [selectedRowIds, setSelectedRowIds] = useState<string[]>([])

  const { ${model.itemsHook.map.name}: data } = ${model.itemsHook.name}()

  // Queries for related models' maps used by the table (passed as separate props)
  ${relatedModels.map((rm) => rm.mapDefinition).join('\n  ')}

  // Convert data map to sorted array for consistent ordering
  const sortedData = useMemo(() =>
    Array.from(data)
      .sort(([id1], [id2]) => id1.localeCompare(id2))
      .map(([, item]) => item),
    [data]
  )

  // Get the selected entity ID based on focused cell
  const selectedEntityId = useMemo(() => {
    if (!focusedCell || focusedCell.rowIndex < 0 || focusedCell.rowIndex >= sortedData.length) {
      return null
    }
    const row = sortedData[focusedCell.rowIndex]
    return row?.id ?? null
  }, [focusedCell, sortedData])

  // Get the selected field name based on focused cell
  const selectedField = useMemo(() => {
    if (!focusedCell || focusedCell.columnId === 'select' || focusedCell.columnId === 'actions') {
      return null
    }
    return focusedCell.columnId
  }, [focusedCell])

  // Callback when cell focus changes in the table
  const handleCellChange = useCallback((args: { rowIndex: number; columnId: string }) => {
    setFocusedCell({ rowIndex: args.rowIndex, columnId: args.columnId })
    // Clear checkbox selection when focusing a cell
    setSelectedRowIds([])
  }, [])

  // Callback when row selection changes (checkbox)
  const handleRowSelectionChange = useCallback((rowIds: string[]) => {
    setSelectedRowIds(rowIds)
    // Clear cell selection when using checkbox selection
    if (rowIds.length > 0) {
      setFocusedCell(null)
    }
  }, [])

  // Clear field filter (go up to entity level)
  const handleClearField = useCallback(() => {
    if (focusedCell) {
      // Keep the entity selected but clear the field
      setFocusedCell({ rowIndex: focusedCell.rowIndex, columnId: '' })
    }
  }, [focusedCell])

  // Clear entity filter (go back to model overview)
  const handleClearEntity = useCallback(() => {
    setFocusedCell(null)
    setSelectedRowIds([])
  }, [])

  ${model.isReadonly
        ? ''
        : `const {${model.itemsHook.updateField.name}: updateFieldMutation, ${model.itemsHook.deleteMany.name}: deleteManyMutation} = ${model.itemsHook.name}()

  function handleDataEdit(editedData: ${model.types.name}[]) {
    editedData.forEach((row) => {
      const oldRow = data?.get(row.id)
      if (!oldRow) return

      // Find which fields changed and update each one individually
      for (const key of Object.keys(row) as Array<keyof ${model.types.name}>) {
        if (key === 'id') continue
        if (oldRow[key] !== row[key]) {
          data?.set(row.id, { ...oldRow, [key]: row[key] })
          void updateFieldMutation({ id: row.id, field: key, value: row[key] } as Parameters<typeof updateFieldMutation>[0])
        }
      }
    })
  }

  function handleRemoveRows(rows: ${model.types.id.name}[]) {
    void deleteManyMutation(rows)
  }
  `}

  return (
    <div className="flex min-h-screen">
      <AdminSidebar />

      <div className="flex flex-col min-h-full w-full max-h-screen overflow-hidden p-4 pr-8">
          <h3 className="font-bold text-[1.75rem]">${model.userFriendlyName}</h3>
          <${model.table.component.name}
            data={sortedData}
            ${model.isReadonly
        ? ''
        : `onDataEdit={handleDataEdit}
              handleAddRow={() => setIsCreateModalOpen(true)}
              handleRemoveRows={handleRemoveRows}`}
            onCellChange={handleCellChange}
            onRowSelectionChange={handleRowSelectionChange}
            ${relatedModels.map((rm) => `${rm.model.table.propName}={${rm.mapName}}`).join('\n                ')}
          />
      </div>
      ${createModal}
      <AuditLogSidebar
        model="${model.name}"
        entityId={selectedEntityId}
        entityIds={selectedRowIds}
        field={selectedField}
        labelField="${model.labelField.name}"
        onClearField={handleClearField}
        onClearEntity={handleClearEntity}
      />
    </div>
  )

}
`;
}
//# sourceMappingURL=model-admin-page.generator.js.map