"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.generateExcelIoPage = generateExcelIoPage;
const Generator = __importStar(require("@postxl/generator"));
function generateExcelIoPage({ context }) {
    const modelNames = [...context.models.values()]
        .sort((a, b) => a.name.localeCompare(b.name))
        .map((model) => `'${model._conjugated.camelCase}'`)
        .join(',\n  ');
    const defaultModel = [...context.models.values()].sort((a, b) => a.name.localeCompare(b.name))[0]?._conjugated.camelCase ?? 'user';
    const imports = Generator.ImportGenerator.from(Generator.toFilePath('./excel-io.page.tsx'))
        .addImport({
        from: Generator.toBackendModuleLocation('@admin/admin-sidebar-nav-content'),
        items: [Generator.toFunctionName('AdminSidebarNavContent')],
    })
        .addImport({ from: Generator.toPackageName('react'), items: [Generator.toFunctionName('useState')] })
        .addImport({
        from: Generator.toBackendModuleLocation('@hooks/use-excel-io'),
        items: [Generator.toFunctionName('useExcelIo')],
    })
        .addImport({
        from: Generator.toPackageName('@postxl/ui-components'),
        items: [
            Generator.toFunctionName('Button'),
            Generator.toFunctionName('Card'),
            Generator.toFunctionName('CardContent'),
            Generator.toFunctionName('CardHeader'),
            Generator.toFunctionName('CardTitle'),
            Generator.toFunctionName('Input'),
            Generator.toFunctionName('Label'),
            Generator.toFunctionName('Select'),
            Generator.toFunctionName('SelectContent'),
            Generator.toFunctionName('SelectItem'),
            Generator.toFunctionName('SelectTrigger'),
            Generator.toFunctionName('SelectValue'),
            Generator.toFunctionName('SidebarTab'),
            Generator.toFunctionName('Textarea'),
        ],
    });
    return /*tsx*/ `
  import { ListTree } from 'lucide-react'
${imports.generate()}

const MODELS = [
  ${modelNames}
] as const

type Status = { type: 'success' | 'error'; message: string }

export default function ExcelIoPage() {
  const [selectedModel, setSelectedModel] = useState<(typeof MODELS)[number]>('${defaultModel}')
  const [filtersJson, setFiltersJson] = useState('')
  const [sortJson, setSortJson] = useState('')
  const [status, setStatus] = useState<Record<string, Status | undefined>>({})

  const {
    isExportingExcel,
    isImportingExcel,
    importInputRef,
    handleExportExcel: exportModelExcel,
    handleImportExcel: importExcelFile,
    openImportDialog,
  } = useExcelIo({ showToasts: false })

  const setStatusKey = (key: string, value?: Status) => {
    setStatus((prev) => ({ ...prev, [key]: value }))
  }

  const handleExportAll = async () => {
    const key = 'export-all'
    setStatusKey(key)

    try {
      await exportModelExcel({ model: undefined })
      setStatusKey(key, { type: 'success', message: 'Export successful' })
    } catch (error) {
      setStatusKey(key, { type: 'error', message: \`Error: ${'${String(error)}'}\` })
    }
  }

  const handleExportModel = async () => {
    const key = 'export-model'
    setStatusKey(key)

    try {
      let parsedFilters: Record<string, unknown> = {}
      if (filtersJson.trim().length > 0) {
        parsedFilters = JSON.parse(filtersJson) as Record<string, unknown>
      }

      let parsedSort: { field: string; direction: 'asc' | 'desc' }[] | undefined
      if (sortJson.trim().length > 0) {
        parsedSort = JSON.parse(sortJson) as { field: string; direction: 'asc' | 'desc' }[]
      }

      await exportModelExcel({ model: selectedModel, filters: parsedFilters, sort: parsedSort })
    } catch (error) {
      setStatusKey(key, { type: 'error', message: \`Error: ${'${String(error)}'}\` })
    }
  }

  const triggerImportExcel = async (file: File) => {
    await importExcelFile(file)
  }

  const statusClass = (value?: Status) => {
    if (!value) {
      return ''
    }

    return value.type === 'success'
      ? 'text-green-700 border-green-300 bg-green-50 dark:text-green-300 dark:border-green-800 dark:bg-green-950/30'
      : 'text-red-700 border-red-300 bg-red-50 dark:text-red-300 dark:border-red-800 dark:bg-red-950/30'
  }

  return (
    <>
      <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-5xl flex-col gap-4">
          <h1 className="text-3xl font-bold">Excel I/O</h1>
          <p className="text-sm text-muted-foreground">Export all data or one model as Excel, and import any Excel file.</p>

          <Card>
            <CardHeader>
              <CardTitle>Export All Models</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <Button onClick={() => void handleExportAll()} disabled={isExportingExcel}>
                {isExportingExcel ? 'Exporting...' : 'Export All to Excel'}
              </Button>
              {status['export-all'] && (
                <div className={\`rounded border p-2 text-sm ${"${statusClass(status['export-all'])}"}\`}>{status['export-all']?.message}</div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Export Single Model</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-1">
                <Label htmlFor="model">Model</Label>
                <Select value={selectedModel} onValueChange={(value) => setSelectedModel(value as (typeof MODELS)[number])}>
                  <SelectTrigger id="model">
                    <SelectValue placeholder="Select model" />
                  </SelectTrigger>
                  <SelectContent>
                    {MODELS.map((model) => (
                      <SelectItem key={model} value={model}>
                        {model}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-1">
                <Label htmlFor="filters">Filters JSON (optional)</Label>
                <Textarea
                  id="filters"
                  value={filtersJson}
                  onChange={(event) => setFiltersJson(event.target.value)}
                  placeholder='{"globalSearch":"demo"}'
                  rows={4}
                />
              </div>

              <div className="space-y-1">
                <Label htmlFor="sort">Sort JSON (optional)</Label>
                <Textarea
                  id="sort"
                  value={sortJson}
                  onChange={(event) => setSortJson(event.target.value)}
                  placeholder='[{"field":"id","direction":"asc"}]'
                  rows={4}
                />
              </div>

              <Button onClick={() => void handleExportModel()} disabled={isExportingExcel}>
                {isExportingExcel ? 'Exporting...' : 'Export Model to Excel'}
              </Button>

              {status['export-model'] && (
                <div className={\`rounded border p-2 text-sm ${"${statusClass(status['export-model'])}"}\`}>
                  {status['export-model']?.message}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Import Excel</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <Label htmlFor="import-file">Upload Excel file</Label>
              <Input
                id="import-file"
                ref={importInputRef}
                type="file"
                accept=".xlsx,.xls"
                disabled={isImportingExcel}
                onChange={(event) => {
                  const file = event.target.files?.[0]
                  if (file) {
                    void triggerImportExcel(file)
                  }
                }}
              />
              <Button type="button" variant="outline" onClick={openImportDialog} disabled={isImportingExcel}>
                {isImportingExcel ? 'Importing...' : 'Select & Import Excel'}
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  )
}
`;
}
//# sourceMappingURL=excel-io-page.generator.js.map