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

export default function StateApiPage() {
  return (
    <DevPortalLayout
      title="State API"
      description="Verwalten Sie den SDK-State für Ihren Tenant"
    >
      <h2>Übersicht</h2>
      <p>
        Die State API ermöglicht das Speichern und Abrufen des kompletten SDK-States.
        Der State enthält alle Compliance-Daten: Use Cases, Risiken, Controls,
        Checkpoints und mehr.
      </p>

      <InfoBox type="info" title="Versionierung">
        Der State wird mit optimistischem Locking gespeichert. Bei jedem Speichern
        wird die Version erhöht. Bei Konflikten erhalten Sie einen 409-Fehler.
      </InfoBox>

      <h2>GET /state/{'{tenantId}'}</h2>
      <p>Lädt den aktuellen SDK-State für einen Tenant.</p>

      <h3>Request</h3>
      <CodeBlock language="bash" filename="cURL">
{`curl -X GET "https://api.breakpilot.io/sdk/v1/state/your-tenant-id" \\
  -H "Authorization: Bearer YOUR_API_KEY"`}
      </CodeBlock>

      <h3>Response (200 OK)</h3>
      <CodeBlock language="json" filename="Response">
{`{
  "success": true,
  "data": {
    "version": "1.0.0",
    "lastModified": "2026-02-04T12:00:00Z",
    "tenantId": "your-tenant-id",
    "userId": "user-123",
    "subscription": "PROFESSIONAL",
    "currentPhase": 1,
    "currentStep": "use-case-workshop",
    "completedSteps": ["use-case-workshop", "screening"],
    "checkpoints": {
      "CP-UC": {
        "checkpointId": "CP-UC",
        "passed": true,
        "validatedAt": "2026-02-01T10:00:00Z",
        "validatedBy": "user-123",
        "errors": [],
        "warnings": []
      }
    },
    "useCases": [
      {
        "id": "uc-1",
        "name": "KI-Kundenanalyse",
        "description": "...",
        "category": "Marketing",
        "stepsCompleted": 5,
        "assessmentResult": {
          "riskLevel": "HIGH",
          "dsfaRequired": true,
          "aiActClassification": "LIMITED"
        }
      }
    ],
    "risks": [...],
    "controls": [...],
    "dsfa": {...},
    "toms": [...],
    "vvt": [...]
  },
  "meta": {
    "version": 5,
    "etag": "W/\\"abc123\\""
  }
}`}
      </CodeBlock>

      <h3>Response (404 Not Found)</h3>
      <CodeBlock language="json" filename="Response">
{`{
  "success": false,
  "error": {
    "code": "NOT_FOUND",
    "message": "No state found for tenant your-tenant-id"
  }
}`}
      </CodeBlock>

      <h2>POST /state</h2>
      <p>Speichert den SDK-State. Unterstützt Versionierung und optimistisches Locking.</p>

      <h3>Request Body</h3>
      <ParameterTable
        parameters={[
          {
            name: 'tenantId',
            type: 'string',
            required: true,
            description: 'Eindeutige Tenant-ID',
          },
          {
            name: 'userId',
            type: 'string',
            required: false,
            description: 'User-ID für Audit-Trail',
          },
          {
            name: 'state',
            type: 'SDKState',
            required: true,
            description: 'Der komplette SDK-State',
          },
          {
            name: 'expectedVersion',
            type: 'number',
            required: false,
            description: 'Erwartete Version für optimistisches Locking',
          },
        ]}
      />

      <h3>Request</h3>
      <CodeBlock language="bash" filename="cURL">
{`curl -X POST "https://api.breakpilot.io/sdk/v1/state" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -H "If-Match: W/\\"abc123\\"" \\
  -d '{
    "tenantId": "your-tenant-id",
    "userId": "user-123",
    "state": {
      "currentPhase": 1,
      "currentStep": "risks",
      "useCases": [...],
      "risks": [...]
    }
  }'`}
      </CodeBlock>

      <h3>Response (200 OK)</h3>
      <CodeBlock language="json" filename="Response">
{`{
  "success": true,
  "data": {
    "tenantId": "your-tenant-id",
    "version": 6,
    "updatedAt": "2026-02-04T12:05:00Z"
  },
  "meta": {
    "etag": "W/\\"def456\\""
  }
}`}
      </CodeBlock>

      <h3>Response (409 Conflict)</h3>
      <CodeBlock language="json" filename="Response">
{`{
  "success": false,
  "error": {
    "code": "CONFLICT",
    "message": "Version conflict: expected 5, but current is 6",
    "details": {
      "expectedVersion": 5,
      "currentVersion": 6
    }
  }
}`}
      </CodeBlock>

      <InfoBox type="warning" title="Konfliktbehandlung">
        Bei einem 409-Fehler sollten Sie den State erneut laden, Ihre Änderungen
        mergen und erneut speichern.
      </InfoBox>

      <h2>DELETE /state/{'{tenantId}'}</h2>
      <p>Löscht den kompletten State für einen Tenant.</p>

      <h3>Request</h3>
      <CodeBlock language="bash" filename="cURL">
{`curl -X DELETE "https://api.breakpilot.io/sdk/v1/state/your-tenant-id" \\
  -H "Authorization: Bearer YOUR_API_KEY"`}
      </CodeBlock>

      <h3>Response (200 OK)</h3>
      <CodeBlock language="json" filename="Response">
{`{
  "success": true,
  "data": {
    "tenantId": "your-tenant-id",
    "deleted": true
  }
}`}
      </CodeBlock>

      <h2>State-Struktur</h2>
      <p>Der SDKState enthält alle Compliance-Daten:</p>

      <CodeBlock language="typescript" filename="types.ts">
{`interface SDKState {
  // Metadata
  version: string
  lastModified: Date

  // Tenant & User
  tenantId: string
  userId: string
  subscription: 'FREE' | 'STARTER' | 'PROFESSIONAL' | 'ENTERPRISE'

  // Progress
  currentPhase: 1 | 2
  currentStep: string
  completedSteps: string[]
  checkpoints: Record<string, CheckpointStatus>

  // Phase 1 Data
  useCases: UseCaseAssessment[]
  activeUseCase: string | null
  screening: ScreeningResult | null
  modules: ServiceModule[]
  requirements: Requirement[]
  controls: Control[]
  evidence: Evidence[]
  checklist: ChecklistItem[]
  risks: Risk[]

  // Phase 2 Data
  aiActClassification: AIActResult | null
  obligations: Obligation[]
  dsfa: DSFA | null
  toms: TOM[]
  retentionPolicies: RetentionPolicy[]
  vvt: ProcessingActivity[]
  documents: LegalDocument[]
  cookieBanner: CookieBannerConfig | null
  consents: ConsentRecord[]
  dsrConfig: DSRConfig | null
  escalationWorkflows: EscalationWorkflow[]

  // UI State
  preferences: UserPreferences
}`}
      </CodeBlock>

      <h2>Beispiel: SDK Integration</h2>
      <CodeBlock language="typescript" filename="sdk-client.ts">
{`import { getSDKApiClient } from '@breakpilot/compliance-sdk'

const client = getSDKApiClient('your-tenant-id')

// State laden
const state = await client.getState()
console.log('Current step:', state.currentStep)
console.log('Use cases:', state.useCases.length)

// State speichern
await client.saveState({
  ...state,
  currentStep: 'risks',
  risks: [...state.risks, newRisk],
})`}
      </CodeBlock>
    </DevPortalLayout>
  )
}
