import { DevPortalLayout, ApiEndpoint, CodeBlock, ParameterTable, InfoBox } from '@/components/DevPortalLayout'

export default function ExportApiPage() {
  return (
    <DevPortalLayout
      title="Export API"
      description="Exportieren Sie Compliance-Daten in verschiedenen Formaten"
    >
      <h2>Uebersicht</h2>
      <p>
        Die Export API ermoeglicht den Download aller Compliance-Daten in
        verschiedenen Formaten fuer Audits, Dokumentation und Archivierung.
      </p>

      <h2>Unterstuetzte Formate</h2>
      <div className="my-4 overflow-x-auto not-prose">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Format</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Beschreibung</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Use Case</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200 text-sm">
            <tr>
              <td className="px-4 py-3 font-mono">json</td>
              <td className="px-4 py-3 text-gray-600">Kompletter State als JSON</td>
              <td className="px-4 py-3 text-gray-600">Backup, Migration, API-Integration</td>
            </tr>
            <tr>
              <td className="px-4 py-3 font-mono">pdf</td>
              <td className="px-4 py-3 text-gray-600">Formatierter PDF-Report</td>
              <td className="px-4 py-3 text-gray-600">Audits, Management-Reports</td>
            </tr>
            <tr>
              <td className="px-4 py-3 font-mono">zip</td>
              <td className="px-4 py-3 text-gray-600">Alle Dokumente als ZIP-Archiv</td>
              <td className="px-4 py-3 text-gray-600">Vollstaendige Dokumentation</td>
            </tr>
          </tbody>
        </table>
      </div>

      <h2>GET /export</h2>
      <p>Exportiert den aktuellen State im gewuenschten Format.</p>

      <h3>Query-Parameter</h3>
      <ParameterTable
        parameters={[
          {
            name: 'format',
            type: 'string',
            required: true,
            description: 'Export-Format: json, pdf, zip',
          },
          {
            name: 'tenantId',
            type: 'string',
            required: true,
            description: 'Tenant-ID',
          },
          {
            name: 'sections',
            type: 'string',
            required: false,
            description: 'Kommaseparierte Liste: useCases,risks,controls,dsfa,toms,vvt (default: alle)',
          },
          {
            name: 'phase',
            type: 'number',
            required: false,
            description: 'Nur bestimmte Phase exportieren: 1 oder 2',
          },
          {
            name: 'language',
            type: 'string',
            required: false,
            description: 'Sprache fuer PDF: de, en (default: de)',
          },
        ]}
      />

      <h2>JSON Export</h2>

      <h3>Request</h3>
      <CodeBlock language="bash" filename="cURL">
{`curl -X GET "https://api.breakpilot.io/sdk/v1/export?format=json&tenantId=your-tenant-id" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -o compliance-export.json`}
      </CodeBlock>

      <h3>Response</h3>
      <CodeBlock language="json" filename="compliance-export.json">
{`{
  "exportedAt": "2026-02-04T12:00:00Z",
  "version": "1.0.0",
  "tenantId": "your-tenant-id",
  "state": {
    "currentPhase": 2,
    "currentStep": "dsfa",
    "completedSteps": [...],
    "useCases": [...],
    "risks": [...],
    "controls": [...],
    "dsfa": {...},
    "toms": [...],
    "vvt": [...]
  },
  "meta": {
    "completionPercentage": 75,
    "lastModified": "2026-02-04T11:55:00Z"
  }
}`}
      </CodeBlock>

      <h2>PDF Export</h2>

      <h3>Request</h3>
      <CodeBlock language="bash" filename="cURL">
{`curl -X GET "https://api.breakpilot.io/sdk/v1/export?format=pdf&tenantId=your-tenant-id&sections=dsfa,toms" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -o compliance-report.pdf`}
      </CodeBlock>

      <h3>PDF Inhalt</h3>
      <p>Das generierte PDF enthaelt:</p>
      <ul>
        <li>Deckblatt mit Tenant-Info und Exportdatum</li>
        <li>Inhaltsverzeichnis</li>
        <li>Executive Summary mit Fortschritt</li>
        <li>Use Case Uebersicht</li>
        <li>Risikoanalyse mit Matrix-Visualisierung</li>
        <li>DSFA (falls generiert)</li>
        <li>TOM-Katalog</li>
        <li>VVT-Auszug</li>
        <li>Checkpoint-Status</li>
      </ul>

      <InfoBox type="info" title="PDF Styling">
        Das PDF folgt einem professionellen Audit-Layout mit Corporate Design.
        Enterprise-Kunden koennen ein Custom-Logo und Farbschema konfigurieren.
      </InfoBox>

      <h2>ZIP Export</h2>

      <h3>Request</h3>
      <CodeBlock language="bash" filename="cURL">
{`curl -X GET "https://api.breakpilot.io/sdk/v1/export?format=zip&tenantId=your-tenant-id" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -o compliance-export.zip`}
      </CodeBlock>

      <h3>ZIP Struktur</h3>
      <CodeBlock language="text" filename="compliance-export.zip">
{`compliance-export/
├── README.md
├── state.json                    # Kompletter State
├── summary.pdf                   # Executive Summary
├── use-cases/
│   ├── uc-1-ki-analyse.json
│   └── uc-2-chatbot.json
├── risks/
│   ├── risk-matrix.pdf
│   └── risks.json
├── documents/
│   ├── dsfa.pdf
│   ├── dsfa.json
│   ├── toms.pdf
│   ├── toms.json
│   ├── vvt.pdf
│   └── vvt.json
├── checkpoints/
│   └── checkpoint-status.json
└── audit-trail/
    └── changes.json`}
      </CodeBlock>

      <h2>SDK Integration</h2>
      <CodeBlock language="typescript" filename="export-examples.ts">
{`import { useSDK, exportToPDF, exportToZIP, downloadExport } from '@breakpilot/compliance-sdk'

// Option 1: Ueber den Hook
function ExportButton() {
  const { exportState } = useSDK()

  const handlePDFExport = async () => {
    const blob = await exportState('pdf')
    downloadExport(blob, 'compliance-report.pdf')
  }

  const handleZIPExport = async () => {
    const blob = await exportState('zip')
    downloadExport(blob, 'compliance-export.zip')
  }

  const handleJSONExport = async () => {
    const blob = await exportState('json')
    downloadExport(blob, 'compliance-state.json')
  }

  return (
    <div className="flex gap-2">
      <button onClick={handlePDFExport}>PDF Export</button>
      <button onClick={handleZIPExport}>ZIP Export</button>
      <button onClick={handleJSONExport}>JSON Export</button>
    </div>
  )
}

// Option 2: Direkte Funktionen
async function exportManually(state: SDKState) {
  // PDF generieren
  const pdfBlob = await exportToPDF(state)
  downloadExport(pdfBlob, \`compliance-\${Date.now()}.pdf\`)

  // ZIP generieren
  const zipBlob = await exportToZIP(state)
  downloadExport(zipBlob, \`compliance-\${Date.now()}.zip\`)
}`}
      </CodeBlock>

      <h2>Command Bar Integration</h2>
      <p>
        Exporte sind auch ueber die Command Bar verfuegbar:
      </p>
      <CodeBlock language="text" filename="Command Bar">
{`Cmd+K → "pdf" → "Als PDF exportieren"
Cmd+K → "zip" → "Als ZIP exportieren"
Cmd+K → "json" → "Als JSON exportieren"`}
      </CodeBlock>

      <h2>Automatisierte Exports</h2>
      <p>
        Fuer regelmaessige Backups oder CI/CD-Integration:
      </p>
      <CodeBlock language="bash" filename="Cron Job">
{`# Taeglicher Backup-Export um 02:00 Uhr
0 2 * * * curl -X GET "https://api.breakpilot.io/sdk/v1/export?format=zip&tenantId=my-tenant" \\
  -H "Authorization: Bearer $API_KEY" \\
  -o "/backups/compliance-$(date +%Y%m%d).zip"`}
      </CodeBlock>

      <InfoBox type="warning" title="Dateigröße">
        ZIP-Exporte koennen bei umfangreichen States mehrere MB gross werden.
        Die API hat ein Timeout von 60 Sekunden. Bei sehr grossen States
        verwenden Sie den asynchronen Export-Endpoint (Enterprise).
      </InfoBox>

      <h2>Fehlerbehandlung</h2>
      <CodeBlock language="typescript" filename="error-handling.ts">
{`import { exportState } from '@breakpilot/compliance-sdk'

try {
  const blob = await exportState('pdf')
  downloadExport(blob, 'report.pdf')
} catch (error) {
  if (error.code === 'EMPTY_STATE') {
    console.error('Keine Daten zum Exportieren vorhanden')
  } else if (error.code === 'GENERATION_FAILED') {
    console.error('PDF-Generierung fehlgeschlagen:', error.message)
  } else if (error.code === 'TIMEOUT') {
    console.error('Export-Timeout - versuchen Sie ZIP fuer grosse States')
  } else {
    console.error('Unbekannter Fehler:', error)
  }
}`}
      </CodeBlock>
    </DevPortalLayout>
  )
}
