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

export default function Phase1GuidePage() {
  return (
    <DevPortalLayout
      title="Phase 1: Assessment Guide"
      description="Schritt-fuer-Schritt durch die Assessment-Phase"
    >
      <h2>Uebersicht Phase 1</h2>
      <p>
        Phase 1 umfasst die Erfassung und Bewertung Ihrer KI-Anwendungsfaelle.
        Am Ende haben Sie eine vollstaendige Risikoanalyse und wissen, welche
        Compliance-Dokumente Sie benoetigen.
      </p>

      <div className="my-6 p-4 bg-blue-50 border border-blue-200 rounded-xl">
        <h3 className="text-lg font-semibold text-blue-900 mb-2">Phase 1 Schritte</h3>
        <ol className="list-decimal list-inside text-blue-800 space-y-1">
          <li>Use Case Workshop</li>
          <li>System Screening</li>
          <li>Compliance Modules</li>
          <li>Requirements</li>
          <li>Controls</li>
          <li>Evidence</li>
          <li>Audit Checklist</li>
          <li>Risk Matrix</li>
        </ol>
      </div>

      <h2>Schritt 1: Use Case Workshop</h2>
      <p>
        Erfassen Sie alle KI-Anwendungsfaelle in Ihrem Unternehmen.
      </p>

      <h3>Code-Beispiel</h3>
      <CodeBlock language="typescript" filename="use-case-workshop.tsx">
{`import { useSDK } from '@breakpilot/compliance-sdk'

function UseCaseForm() {
  const { updateUseCase, state } = useSDK()

  const handleCreateUseCase = async () => {
    await updateUseCase({
      id: \`uc-\${Date.now()}\`,
      name: 'KI-gestuetzte Kundenanalyse',
      description: 'Analyse von Kundenverhalten mittels ML',
      category: 'Marketing',
      department: 'Marketing & Sales',
      dataTypes: ['Kundendaten', 'Verhaltensdaten', 'Transaktionen'],
      aiCapabilities: ['Profiling', 'Vorhersage'],
      stepsCompleted: 0,
    })
  }

  return (
    <div>
      <h2>Use Cases: {state.useCases.length}</h2>
      <button onClick={handleCreateUseCase}>
        Use Case hinzufuegen
      </button>

      {state.useCases.map(uc => (
        <div key={uc.id}>
          <h3>{uc.name}</h3>
          <p>{uc.description}</p>
        </div>
      ))}
    </div>
  )
}`}
      </CodeBlock>

      <InfoBox type="info" title="Checkpoint CP-UC">
        Nach dem Use Case Workshop muss mindestens ein Use Case angelegt sein,
        um zum naechsten Schritt zu gelangen.
      </InfoBox>

      <h2>Schritt 2: System Screening</h2>
      <p>
        Das Screening bewertet jeden Use Case hinsichtlich Datenschutz und AI Act.
      </p>

      <h3>Code-Beispiel</h3>
      <CodeBlock language="typescript" filename="screening.tsx">
{`import { useSDK } from '@breakpilot/compliance-sdk'

function ScreeningView() {
  const { state, dispatch } = useSDK()

  const completeScreening = (useCaseId: string, result: ScreeningResult) => {
    dispatch({
      type: 'UPDATE_USE_CASE',
      payload: {
        id: useCaseId,
        screeningResult: result,
        // Ergebnis bestimmt weitere Pflichten
        assessmentResult: {
          riskLevel: result.aiActRisk,
          dsfaRequired: result.dsfaRequired,
          aiActClassification: result.aiActClassification,
        },
      },
    })
  }

  // Screening-Fragen beantworten
  const screeningQuestions = [
    'Werden personenbezogene Daten verarbeitet?',
    'Erfolgt automatisierte Entscheidungsfindung?',
    'Werden besondere Datenkategorien verarbeitet?',
    'Erfolgt Profiling?',
    'Werden Daten in Drittlaender uebermittelt?',
  ]

  return (
    <div>
      {screeningQuestions.map((question, i) => (
        <label key={i} className="block">
          <input type="checkbox" />
          {question}
        </label>
      ))}
    </div>
  )
}`}
      </CodeBlock>

      <h2>Schritt 3: Compliance Modules</h2>
      <p>
        Basierend auf dem Screening werden relevante Compliance-Module aktiviert.
      </p>

      <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">Modul</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aktiviert wenn</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200 text-sm">
            <tr>
              <td className="px-4 py-3 font-medium">DSGVO Basis</td>
              <td className="px-4 py-3 text-gray-600">Immer (personenbezogene Daten)</td>
            </tr>
            <tr>
              <td className="px-4 py-3 font-medium">DSFA</td>
              <td className="px-4 py-3 text-gray-600">Hohes Risiko, Profiling, Art. 9 Daten</td>
            </tr>
            <tr>
              <td className="px-4 py-3 font-medium">AI Act</td>
              <td className="px-4 py-3 text-gray-600">KI-basierte Entscheidungen</td>
            </tr>
            <tr>
              <td className="px-4 py-3 font-medium">NIS2</td>
              <td className="px-4 py-3 text-gray-600">Kritische Infrastruktur</td>
            </tr>
          </tbody>
        </table>
      </div>

      <h2>Schritt 4: Requirements</h2>
      <p>
        Fuer jedes aktivierte Modul werden spezifische Anforderungen generiert.
      </p>

      <CodeBlock language="typescript" filename="requirements.tsx">
{`import { useSDK } from '@breakpilot/compliance-sdk'

function RequirementsView() {
  const { state } = useSDK()

  // Requirements nach Modul gruppieren
  const byModule = state.requirements.reduce((acc, req) => {
    const module = req.module || 'general'
    if (!acc[module]) acc[module] = []
    acc[module].push(req)
    return acc
  }, {})

  return (
    <div>
      {Object.entries(byModule).map(([module, reqs]) => (
        <div key={module}>
          <h3>{module}</h3>
          <ul>
            {reqs.map(req => (
              <li key={req.id}>
                <strong>{req.title}</strong>
                <p>{req.description}</p>
                <span>Status: {req.status}</span>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  )
}`}
      </CodeBlock>

      <h2>Schritt 5: Controls</h2>
      <p>
        Definieren Sie Kontrollen fuer jede Anforderung.
      </p>

      <CodeBlock language="typescript" filename="controls.tsx">
{`import { useSDK } from '@breakpilot/compliance-sdk'

function ControlsView() {
  const { updateControl, state } = useSDK()

  const addControl = (requirementId: string) => {
    updateControl({
      id: \`ctrl-\${Date.now()}\`,
      requirementId,
      title: 'Zugriffskontrolle implementieren',
      description: 'Role-based access control fuer alle Datenzugaenge',
      type: 'TECHNICAL',
      status: 'PLANNED',
      implementationDate: null,
      owner: 'IT-Abteilung',
    })
  }

  return (
    <div>
      <h2>Controls: {state.controls.length}</h2>

      {state.requirements.map(req => (
        <div key={req.id}>
          <h3>{req.title}</h3>
          <p>Controls: {state.controls.filter(c => c.requirementId === req.id).length}</p>
          <button onClick={() => addControl(req.id)}>
            Control hinzufuegen
          </button>
        </div>
      ))}
    </div>
  )
}`}
      </CodeBlock>

      <InfoBox type="warning" title="Checkpoint CP-CTRL">
        Jede Requirement muss mindestens ein Control haben, bevor Sie
        zur Evidence-Phase uebergehen koennen.
      </InfoBox>

      <h2>Schritt 6: Evidence</h2>
      <p>
        Dokumentieren Sie Nachweise fuer implementierte Controls.
      </p>

      <CodeBlock language="typescript" filename="evidence.tsx">
{`import { useSDK } from '@breakpilot/compliance-sdk'

function EvidenceUpload({ controlId }: { controlId: string }) {
  const { dispatch } = useSDK()

  const addEvidence = (file: File) => {
    dispatch({
      type: 'ADD_EVIDENCE',
      payload: {
        id: \`ev-\${Date.now()}\`,
        controlId,
        title: file.name,
        type: 'DOCUMENT',
        uploadedAt: new Date().toISOString(),
        fileType: file.type,
        // In Produktion: Upload zu Storage
      },
    })
  }

  return (
    <input
      type="file"
      onChange={(e) => e.target.files?.[0] && addEvidence(e.target.files[0])}
    />
  )
}`}
      </CodeBlock>

      <h2>Schritt 7: Audit Checklist</h2>
      <p>
        Die Checkliste fasst alle Compliance-Punkte zusammen.
      </p>

      <h2>Schritt 8: Risk Matrix</h2>
      <p>
        Bewerten Sie alle identifizierten Risiken nach Likelihood und Impact.
      </p>

      <CodeBlock language="typescript" filename="risk-matrix.tsx">
{`import { useSDK, calculateRiskScore, getRiskSeverityFromScore } from '@breakpilot/compliance-sdk'

function RiskMatrix() {
  const { addRisk, state } = useSDK()

  const createRisk = () => {
    const likelihood = 3 // 1-5
    const impact = 4     // 1-5
    const score = calculateRiskScore(likelihood, impact) // 12
    const severity = getRiskSeverityFromScore(score) // 'HIGH'

    addRisk({
      id: \`risk-\${Date.now()}\`,
      title: 'Unbefugter Datenzugriff',
      description: 'Risiko durch unzureichende Zugriffskontrolle',
      likelihood,
      impact,
      inherentScore: score,
      severity,
      category: 'Security',
      mitigations: [],
      residualScore: null,
    })
  }

  return (
    <div>
      <h2>Risiken: {state.risks.length}</h2>

      {/* 5x5 Matrix Visualisierung */}
      <div className="grid grid-cols-5 gap-1">
        {[5,4,3,2,1].map(likelihood => (
          [1,2,3,4,5].map(impact => {
            const score = likelihood * impact
            const risksHere = state.risks.filter(
              r => r.likelihood === likelihood && r.impact === impact
            )
            return (
              <div
                key={\`\${likelihood}-\${impact}\`}
                className={\`p-2 \${score >= 15 ? 'bg-red-500' : score >= 8 ? 'bg-yellow-500' : 'bg-green-500'}\`}
              >
                {risksHere.length > 0 && (
                  <span className="text-white">{risksHere.length}</span>
                )}
              </div>
            )
          })
        ))}
      </div>

      <button onClick={createRisk}>Risiko hinzufuegen</button>
    </div>
  )
}`}
      </CodeBlock>

      <InfoBox type="success" title="Phase 1 abgeschlossen">
        Nach erfolgreicher Bewertung aller Risiken koennen Sie zu Phase 2
        uebergehen. Der Checkpoint CP-RISK validiert, dass alle Risiken
        eine Severity-Bewertung haben.
      </InfoBox>

      <h2>Navigation nach Phase 2</h2>
      <CodeBlock language="typescript" filename="phase-transition.tsx">
{`import { useSDK } from '@breakpilot/compliance-sdk'

function PhaseTransition() {
  const { validateCheckpoint, goToStep, phase1Completion } = useSDK()

  const handleContinueToPhase2 = async () => {
    // Alle Phase-1-Checkpoints pruefen
    const cpRisk = await validateCheckpoint('CP-RISK')

    if (cpRisk.passed) {
      goToStep('ai-act-classification') // Erster Schritt Phase 2
    } else {
      console.error('Checkpoint nicht bestanden:', cpRisk.errors)
    }
  }

  return (
    <div>
      <p>Phase 1 Fortschritt: {phase1Completion}%</p>

      {phase1Completion === 100 && (
        <button onClick={handleContinueToPhase2}>
          Weiter zu Phase 2
        </button>
      )}
    </div>
  )
}`}
      </CodeBlock>
    </DevPortalLayout>
  )
}
