"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'),
        ],
    })
        .addImport({
        from: model.types.filter.field.location,
        items: [
            model.types.filter.field.name,
            model.types.filter.fieldType.name,
            model.types.filter.config.name,
            model.types.filter.type.name,
        ],
    })
        .addImport({
        from: Generator.toPackageName('@types'),
        items: [Generator.toTypeName('SortState')],
    })
        .addImport({
        from: Generator.toPackageName('@tanstack/react-router'),
        items: [Generator.toFunctionName('useNavigate')],
    });
    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.id)
            .addImport({ from: Generator.toPackageName('sonner'), items: [Generator.toFunctionName('toast')] })
            .addImport({ from: model.forms.createModal.location, items: [model.forms.createModal.name] });
        // In case 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 `
import { SidebarInset, SidebarProvider, SidebarTrigger, useDebouncedCallback } from '@postxl/ui-components'
import useSessionStorageState from 'use-session-storage-state'
${imports.generate()}

type CellSelection = {
  rowIndex: number
  columnId: string
}

const STORAGE_KEY = 'audit-log-collapse-state'

type ${model.admin.page.pageComponent.name}Props = {
  selectedKey?: string
}

export default function ${model.admin.page.pageComponent.name}({ selectedKey }: ${model.admin.page.pageComponent.name}Props) {
  const navigate = useNavigate()
  ${createModalHook}

  // audit log sidebar collapse state
  const [collapseState, setCollapseState] = useSessionStorageState<boolean>(STORAGE_KEY, {
    defaultValue: false,
  })
  
  // 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 [filters, setFilters] = useState<${model.types.filter.type.name}>({})

  // Server-side sorting state (backend applies default sort by ID if empty)
  const [sortState, setSortState] = useState<SortState<${model.types.filter.fieldType.name}>>([])

  // Global search input state (debounced filter update happens via handleSearchInputChange)
  const [searchInput, setSearchInput] = useState('')

   const {
    ${model.itemsHook.filteredList.name}: filteredDataList,
    hasNextPage,
    fetchNextPage,
    total,
    ${model.isReadonly ? '' : `${model.itemsHook.updateField.name}: updateFieldMutation, ${model.itemsHook.deleteMany.name}: deleteManyMutation,`}
  } = ${model.itemsHook.name}({ filters, sort: sortState })

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


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

  // 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([])
  }, [])

  const handleFilterChange = useCallback((key: ${model.types.filter.fieldType.name} | 'globalSearch', val: any) => {
    setFilters((prev) => {
      if (!val || (Array.isArray(val) && val.length === 0)) {
        const { [key]: _removed, ...rest } = prev
        return rest
      }
      return { ...prev, [key]: val }
    })
  }, [])

  // Debounced filter change for global search
  const debouncedFilterChange = useDebouncedCallback(handleFilterChange, 300)

  // Handler for search input that updates state immediately and triggers debounced filter
  const handleSearchInputChange = useCallback((value: string) => {
    setSearchInput(value)
    debouncedFilterChange('globalSearch', value)
  }, [debouncedFilterChange])

  // Handle row click - navigate to URL with keyField value
  const handleRowClick = useCallback((key: string | null) => {
    if (key) {
      void navigate({ to: '${model.admin.page.route}/$key', params: { key } })
    } else {
      void navigate({ to: '${model.admin.page.route}' })
    }
  }, [navigate])

  ${model.isReadonly
        ? ''
        : `// Handle individual cell updates - directly call mutation for the specific cell
  const handleCellUpdate = useCallback((args: { rowIndex: number; columnId: string; value: unknown }) => {
    const row = filteredDataList?.[args.rowIndex]
    if (!row) return

    // Call mutation directly for this specific cell change
    void updateFieldMutation({ id: row.id, field: args.columnId, value: args.value } as Parameters<typeof updateFieldMutation>[0])
  }, [filteredDataList, updateFieldMutation])

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

  return (
    ${model.isReadonly ? '' : '<>'}
      <SidebarProvider open={collapseState} onOpenChange={setCollapseState}>
        <AdminSidebar collapsible="none" />

        <SidebarInset className="p-4 overflow-hidden gap-4">
          <h3 className="font-bold text-[1.75rem]">${model.userFriendlyName}</h3>
          <${model.table.component.name}
            data={filteredDataList ?? []}
            filters={filters}
            onFilterChange={(filterKey, val) => {
            const config = ${model.types.filter.config.name}[filterKey]
              if (config.valueType === 'boolean') {
                handleFilterChange(
                  config.filterKey,
                  (val as string[]).map((v) => v === 'true'),
                )
              } else {
                handleFilterChange(config.filterKey, val)
              }
            }}
            searchInput={searchInput}
            onSearchInputChange={handleSearchInputChange}
            sort={sortState}
            onSortChange={setSortState}
            ${model.isReadonly
        ? ''
        : `onCellUpdate={handleCellUpdate}
              handleAddRow={() => setIsCreateModalOpen(true)}
              handleRemoveRows={handleRemoveRows}`}
            onCellChange={handleCellChange}
            onRowSelectionChange={handleRowSelectionChange}
            selectedKey={selectedKey}
            onRowClick={handleRowClick}
            keyField="${model.keyField.name}"
            hasNextPage={hasNextPage}
            fetchNextPage={fetchNextPage}
            total={total}
            ${relatedModels.map((rm) => `${rm.model.table.propName}={${rm.mapName}}`).join('\n                ')}
          />
        </SidebarInset>
        
        <SidebarTrigger />
    
        <AuditLogSidebar
          side="right"
          collapsible="offcanvas"
          model="${model.name}"
          entityId={selectedEntityId}
          entityIds={selectedRowIds}
          field={selectedField}
          labelField="${model.labelField.name}"
          onClearField={handleClearField}
          onClearEntity={handleClearEntity}
        />
      </SidebarProvider>
    
      ${createModal}
    ${model.isReadonly ? '' : '</>'}
  )
}
`;
}
//# sourceMappingURL=model-admin-page.generator.js.map