'use client'

/**
 * Production Readiness Backlog
 *
 * Comprehensive checklist of items needed before going live with BreakPilot
 * Includes CI/CD, Security, RBAC, Data Protection, and Release Workflows
 */

import AdminLayout from '@/components/admin/AdminLayout'
import { useState, useEffect } from 'react'

interface BacklogItem {
  id: string
  title: string
  description: string
  category: string
  priority: 'critical' | 'high' | 'medium' | 'low'
  status: 'not_started' | 'in_progress' | 'review' | 'completed' | 'blocked'
  assignee?: string
  dueDate?: string
  notes?: string
  subtasks?: { id: string; title: string; completed: boolean }[]
}

interface BacklogCategory {
  id: string
  name: string
  icon: React.ReactNode
  color: string
  description: string
}

const categories: BacklogCategory[] = [
  {
    id: 'modules',
    name: 'Module Progress',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
      </svg>
    ),
    color: 'bg-violet-100 text-violet-700 border-violet-300',
    description: 'Fertigstellungsgrad aller Services & Module',
  },
  {
    id: 'cicd',
    name: 'CI/CD Pipelines',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
      </svg>
    ),
    color: 'bg-blue-100 text-blue-700 border-blue-300',
    description: 'Build, Test & Deployment Automation',
  },
  {
    id: 'security',
    name: 'Security & Vulnerability',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
      </svg>
    ),
    color: 'bg-red-100 text-red-700 border-red-300',
    description: 'Security Scans, Dependency Checks & Penetration Testing',
  },
  {
    id: 'testing',
    name: 'Testing & Quality',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
      </svg>
    ),
    color: 'bg-emerald-100 text-emerald-700 border-emerald-300',
    description: 'Unit Tests, Integration Tests & E2E Testing',
  },
  {
    id: 'rbac',
    name: 'RBAC & Access Control',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
      </svg>
    ),
    color: 'bg-purple-100 text-purple-700 border-purple-300',
    description: 'Developer Roles, Permissions & Team Management',
  },
  {
    id: 'git',
    name: 'Git & Branch Protection',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
      </svg>
    ),
    color: 'bg-orange-100 text-orange-700 border-orange-300',
    description: 'Protected Branches, Merge Requests & Code Reviews',
  },
  {
    id: 'release',
    name: 'Release Management',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
      </svg>
    ),
    color: 'bg-green-100 text-green-700 border-green-300',
    description: 'Versioning, Changelog & Release Notes',
  },
  {
    id: 'data',
    name: 'Data Protection',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
      </svg>
    ),
    color: 'bg-cyan-100 text-cyan-700 border-cyan-300',
    description: 'Backup, Migration & Customer Data Safety',
  },
  {
    id: 'compliance',
    name: 'Compliance & SBOM',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
    ),
    color: 'bg-teal-100 text-teal-700 border-teal-300',
    description: 'SBOM, Lizenzen & Open Source Compliance',
  },
  {
    id: 'approval',
    name: 'Approval Workflow',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
      </svg>
    ),
    color: 'bg-indigo-100 text-indigo-700 border-indigo-300',
    description: 'Developer Approval, QA Sign-off & Release Gates',
  },
]

const initialBacklogItems: BacklogItem[] = [
  // ==================== MODULE PROGRESS ====================
  {
    id: 'mod-1',
    title: 'Consent Service (Go) - 85% fertig',
    description: 'DSGVO Consent Management Microservice - Near Production Ready',
    category: 'modules',
    priority: 'high',
    status: 'in_progress',
    notes: 'Port 8081. 19 Test-Dateien vorhanden. JWT Auth, OAuth 2.0, TOTP 2FA, DSR Workflow, Matrix/Jitsi Integration.',
    subtasks: [
      { id: 'mod-1-1', title: 'Core Consent API (CRUD, Versioning)', completed: true },
      { id: 'mod-1-2', title: 'Authentication (JWT, OAuth 2.0, TOTP)', completed: true },
      { id: 'mod-1-3', title: 'DSR Workflow (Art. 15-21)', completed: true },
      { id: 'mod-1-4', title: 'Email Templates & Notifications', completed: true },
      { id: 'mod-1-5', title: 'Matrix/Jitsi Integration', completed: true },
      { id: 'mod-1-6', title: 'Performance Tests (High-Load)', completed: false },
      { id: 'mod-1-7', title: 'E2E API Contract Tests', completed: false },
    ],
  },
  {
    id: 'mod-2',
    title: 'School Service (Go) - 75% fertig',
    description: 'Klassen, Noten, Zeugnisse Microservice',
    category: 'modules',
    priority: 'high',
    status: 'in_progress',
    notes: 'Port 8084. 6 Test-Dateien. Zeugnis-Workflow mit RBAC (Fachlehrer, Klassenlehrer, Schulleitung).',
    subtasks: [
      { id: 'mod-2-1', title: 'Klassen & Schueler Management', completed: true },
      { id: 'mod-2-2', title: 'Noten-System mit Statistik', completed: true },
      { id: 'mod-2-3', title: 'Zeugnis-Workflow & Rollen', completed: true },
      { id: 'mod-2-4', title: 'Exam Variant Generation (LLM)', completed: true },
      { id: 'mod-2-5', title: 'Seed Data Generator', completed: true },
      { id: 'mod-2-6', title: 'Integration Tests zwischen Services', completed: false },
      { id: 'mod-2-7', title: 'Performance Tests (grosse Klassen)', completed: false },
      { id: 'mod-2-8', title: 'Trend-Analyse & Comparative Analytics', completed: false },
    ],
  },
  {
    id: 'mod-3',
    title: 'Billing Service (Go) - 80% fertig',
    description: 'Stripe Integration & Task-Based Billing',
    category: 'modules',
    priority: 'high',
    status: 'in_progress',
    notes: 'Port 8083. 5 Test-Dateien. Task-Konsum mit 5-Monats-Carryover, Fair Use Mode.',
    subtasks: [
      { id: 'mod-3-1', title: 'Subscription Lifecycle', completed: true },
      { id: 'mod-3-2', title: 'Stripe Checkout & Webhooks', completed: true },
      { id: 'mod-3-3', title: 'Task-Based Consumption Tracking', completed: true },
      { id: 'mod-3-4', title: 'Feature Gating / Entitlements', completed: true },
      { id: 'mod-3-5', title: 'Customer Portal Integration', completed: true },
      { id: 'mod-3-6', title: 'Refund & Chargeback Handling', completed: false },
      { id: 'mod-3-7', title: 'Advanced Analytics & Reporting', completed: false },
    ],
  },
  {
    id: 'mod-4',
    title: 'Klausur Service (Python) - 70% fertig',
    description: 'BYOEH Abitur-Klausurkorrektur System',
    category: 'modules',
    priority: 'critical',
    status: 'in_progress',
    notes: 'Port 8086. 2 Test-Dateien. BYOEH mit AES-256-GCM Encryption, Qdrant Vector DB, Key-Sharing.',
    subtasks: [
      { id: 'mod-4-1', title: 'BYOEH Upload & Encryption', completed: true },
      { id: 'mod-4-2', title: 'Key-Sharing zwischen Pruefern', completed: true },
      { id: 'mod-4-3', title: 'Qdrant RAG Integration', completed: true },
      { id: 'mod-4-4', title: 'RBAC fuer Pruefer-Rollen', completed: true },
      { id: 'mod-4-5', title: 'OCR Pipeline Implementation', completed: false },
      { id: 'mod-4-6', title: 'KI-gestuetzte Korrektur API', completed: false },
      { id: 'mod-4-7', title: 'Gutachten-Generierung', completed: false },
      { id: 'mod-4-8', title: 'Frontend: KorrekturPage fertigstellen', completed: false },
    ],
  },
  {
    id: 'mod-5',
    title: 'Admin Frontend (Next.js) - 60% fertig',
    description: 'Next.js 15 Admin Dashboard',
    category: 'modules',
    priority: 'high',
    status: 'in_progress',
    notes: 'Port 3000. Nur 1 Test-Datei! Viele Admin-Seiten sind nur Skelett-Implementierungen.',
    subtasks: [
      { id: 'mod-5-1', title: 'AdminLayout & Navigation', completed: true },
      { id: 'mod-5-2', title: 'SBOM & Architecture Pages', completed: true },
      { id: 'mod-5-3', title: 'Security Dashboard', completed: true },
      { id: 'mod-5-4', title: 'Backlog Page', completed: true },
      { id: 'mod-5-5', title: 'Consent Management Page', completed: true },
      { id: 'mod-5-6', title: 'Edu-Search Implementation', completed: false },
      { id: 'mod-5-7', title: 'DSMS Page Implementation', completed: false },
      { id: 'mod-5-8', title: 'Component Unit Tests', completed: false },
      { id: 'mod-5-9', title: 'E2E Tests mit Playwright', completed: false },
      { id: 'mod-5-10', title: 'Authentication Implementation', completed: false },
    ],
  },
  {
    id: 'mod-6',
    title: 'Backend Studio (Python) - 65% fertig',
    description: 'Lehrer-Frontend Module (FastAPI)',
    category: 'modules',
    priority: 'medium',
    status: 'in_progress',
    notes: 'Port 8000. Keine dedizierten Tests! Integration mit allen APIs.',
    subtasks: [
      { id: 'mod-6-1', title: 'Studio Router & Module Loading', completed: true },
      { id: 'mod-6-2', title: 'School Module UI', completed: true },
      { id: 'mod-6-3', title: 'Meetings/Jitsi Integration', completed: true },
      { id: 'mod-6-4', title: 'Customer Portal (Slim)', completed: true },
      { id: 'mod-6-5', title: 'Dev Admin Panel', completed: true },
      { id: 'mod-6-6', title: 'Component Unit Tests', completed: false },
      { id: 'mod-6-7', title: 'UI Component Dokumentation', completed: false },
      { id: 'mod-6-8', title: 'Accessibility Compliance', completed: false },
    ],
  },
  {
    id: 'mod-7',
    title: 'DSMS/IPFS Service - 40% fertig',
    description: 'Dezentrales Speichersystem',
    category: 'modules',
    priority: 'low',
    status: 'not_started',
    notes: 'Port 8082. Keine Tests! Grundstruktur vorhanden aber Core-Logic fehlt.',
    subtasks: [
      { id: 'mod-7-1', title: 'Service Struktur', completed: true },
      { id: 'mod-7-2', title: 'IPFS Configuration', completed: true },
      { id: 'mod-7-3', title: 'Upload/Download Handlers', completed: false },
      { id: 'mod-7-4', title: 'Encryption/Decryption Layer', completed: false },
      { id: 'mod-7-5', title: 'Pinning Strategy', completed: false },
      { id: 'mod-7-6', title: 'Replication Logic', completed: false },
      { id: 'mod-7-7', title: 'Tests & Dokumentation', completed: false },
    ],
  },
  {
    id: 'mod-8',
    title: 'Security Module (Python) - 75% fertig',
    description: 'DevSecOps Dashboard & Scans',
    category: 'modules',
    priority: 'medium',
    status: 'in_progress',
    notes: 'Teil von Backend. Keine dedizierten Tests! Gitleaks, Semgrep, Bandit, Trivy Integration.',
    subtasks: [
      { id: 'mod-8-1', title: 'Security Tool Status API', completed: true },
      { id: 'mod-8-2', title: 'Findings Aggregation', completed: true },
      { id: 'mod-8-3', title: 'Report Parsing (alle Tools)', completed: true },
      { id: 'mod-8-4', title: 'SBOM Generation (CycloneDX)', completed: true },
      { id: 'mod-8-5', title: 'Scan Triggering', completed: true },
      { id: 'mod-8-6', title: 'Unit Tests fuer Parser', completed: false },
      { id: 'mod-8-7', title: 'Vulnerability Tracking', completed: false },
      { id: 'mod-8-8', title: 'Compliance Reporting (SOC2)', completed: false },
    ],
  },

  // ==================== TESTING & QUALITY ====================
  {
    id: 'test-1',
    title: 'Test Coverage Erhöhen - Consent Service',
    description: 'Integration & E2E Tests fuer produktionskritischen Service',
    category: 'testing',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'test-1-1', title: 'E2E API Tests mit echter DB', completed: false },
      { id: 'test-1-2', title: 'Load Testing mit k6 oder vegeta', completed: false },
      { id: 'test-1-3', title: 'Edge Cases in DSR Workflow', completed: false },
    ],
  },
  {
    id: 'test-2',
    title: 'Admin Frontend Test Suite',
    description: 'Component & E2E Tests fuer Next.js Admin',
    category: 'testing',
    priority: 'critical',
    status: 'not_started',
    notes: 'Aktuell nur 1 Test-Datei! Kritischer Mangel.',
    subtasks: [
      { id: 'test-2-1', title: 'Jest/Vitest fuer Component Tests', completed: false },
      { id: 'test-2-2', title: 'Playwright E2E Setup', completed: false },
      { id: 'test-2-3', title: 'API Mock Layer', completed: false },
      { id: 'test-2-4', title: 'Visual Regression Tests', completed: false },
    ],
  },
  {
    id: 'test-3',
    title: 'Klausur Service Tests erweitern',
    description: 'OCR & KI-Korrektur Pipeline testen',
    category: 'testing',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'test-3-1', title: 'BYOEH Encryption Tests', completed: true },
      { id: 'test-3-2', title: 'Key-Sharing Tests', completed: true },
      { id: 'test-3-3', title: 'OCR Pipeline Integration Tests', completed: false },
      { id: 'test-3-4', title: 'Large File Upload Tests', completed: false },
    ],
  },
  {
    id: 'test-4',
    title: 'Security Module Unit Tests',
    description: 'Parser-Funktionen und Findings-Aggregation testen',
    category: 'testing',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'test-4-1', title: 'Gitleaks Parser Tests', completed: false },
      { id: 'test-4-2', title: 'Trivy Parser Tests', completed: false },
      { id: 'test-4-3', title: 'SBOM Generation Tests', completed: false },
      { id: 'test-4-4', title: 'Mock Security Reports', completed: false },
    ],
  },

  // ==================== CI/CD PIPELINES ====================
  {
    id: 'cicd-1',
    title: 'GitHub Actions Workflow Setup',
    description: 'Basis CI/CD Pipeline mit GitHub Actions aufsetzen',
    category: 'cicd',
    priority: 'critical',
    status: 'completed',
    notes: 'Implementiert in .github/workflows/ci.yml - Go, Python, Node.js Tests, Docker Build & Push zu GHCR, Staging/Production Deployment',
    subtasks: [
      { id: 'cicd-1-1', title: 'Build-Job fuer alle Services (Go, Python, Node)', completed: true },
      { id: 'cicd-1-2', title: 'Test-Job mit Coverage Report', completed: true },
      { id: 'cicd-1-3', title: 'Docker Image Build & Push', completed: true },
      { id: 'cicd-1-4', title: 'Deploy to Staging Environment', completed: true },
    ],
  },
  {
    id: 'cicd-2',
    title: 'Staging Environment einrichten',
    description: 'Separate Staging-Umgebung fuer Pre-Production Tests',
    category: 'cicd',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'cicd-2-1', title: 'Staging Server/Cluster provisionieren', completed: false },
      { id: 'cicd-2-2', title: 'Staging Datenbank mit anonymisierten Daten', completed: false },
      { id: 'cicd-2-3', title: 'Automatisches Deployment bei Merge to main', completed: false },
    ],
  },
  {
    id: 'cicd-3',
    title: 'Production Deployment Pipeline',
    description: 'Kontrolliertes Deployment in Production mit Rollback',
    category: 'cicd',
    priority: 'critical',
    status: 'not_started',
    subtasks: [
      { id: 'cicd-3-1', title: 'Blue-Green oder Canary Deployment Strategy', completed: false },
      { id: 'cicd-3-2', title: 'Automatischer Rollback bei Fehlern', completed: false },
      { id: 'cicd-3-3', title: 'Health Check nach Deployment', completed: false },
      { id: 'cicd-3-4', title: 'Deployment Notifications (Slack/Email)', completed: false },
    ],
  },

  // Security & Vulnerability
  {
    id: 'sec-1',
    title: 'Dependency Vulnerability Scanning',
    description: 'Automatische Pruefung auf bekannte Schwachstellen in Dependencies',
    category: 'security',
    priority: 'critical',
    status: 'completed',
    notes: 'Implementiert in .github/dependabot.yml - Go, Python, npm, GitHub Actions und Docker Dependencies werden woechentlich geprueft',
    subtasks: [
      { id: 'sec-1-1', title: 'Dependabot fuer Go aktivieren', completed: true },
      { id: 'sec-1-2', title: 'Dependabot fuer Python aktivieren', completed: true },
      { id: 'sec-1-3', title: 'Dependabot fuer npm aktivieren', completed: true },
      { id: 'sec-1-4', title: 'CI-Job: Block Merge bei kritischen Vulnerabilities', completed: true },
    ],
  },
  {
    id: 'sec-2',
    title: 'Container Image Scanning',
    description: 'Sicherheitspruefung aller Docker Images vor Deployment',
    category: 'security',
    priority: 'high',
    status: 'completed',
    notes: 'Implementiert in .github/workflows/security.yml - Trivy scannt alle Docker Images',
    subtasks: [
      { id: 'sec-2-1', title: 'Trivy oder Snyk in CI integrieren', completed: true },
      { id: 'sec-2-2', title: 'Base Image Policy definieren', completed: true },
      { id: 'sec-2-3', title: 'Scan Report bei jedem Build', completed: true },
    ],
  },
  {
    id: 'sec-3',
    title: 'SAST (Static Application Security Testing)',
    description: 'Code-Analyse auf Sicherheitsluecken',
    category: 'security',
    priority: 'high',
    status: 'completed',
    notes: 'Implementiert in .github/workflows/security.yml - Gosec, Bandit, npm audit',
    subtasks: [
      { id: 'sec-3-1', title: 'CodeQL fuer Go/Python aktivieren', completed: true },
      { id: 'sec-3-2', title: 'Semgrep Regeln konfigurieren', completed: false },
      { id: 'sec-3-3', title: 'OWASP Top 10 Checks integrieren', completed: true },
    ],
  },
  {
    id: 'sec-4',
    title: 'Secret Scanning',
    description: 'Verhindern, dass Secrets in Git landen',
    category: 'security',
    priority: 'critical',
    status: 'completed',
    notes: 'Implementiert in .github/workflows/security.yml - TruffleHog und GitLeaks scannen nach Secrets',
    subtasks: [
      { id: 'sec-4-1', title: 'GitHub Secret Scanning aktivieren', completed: true },
      { id: 'sec-4-2', title: 'Pre-commit Hook mit gitleaks', completed: true },
      { id: 'sec-4-3', title: 'Historische Commits scannen', completed: true },
    ],
  },

  // RBAC & Access Control
  {
    id: 'rbac-1',
    title: 'GitHub Team & Repository Permissions',
    description: 'Team-basierte Zugriffsrechte auf Repository',
    category: 'rbac',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'rbac-1-1', title: 'Team "Maintainers" erstellen (Full Access)', completed: false },
      { id: 'rbac-1-2', title: 'Team "Developers" erstellen (Write Access)', completed: false },
      { id: 'rbac-1-3', title: 'Team "Reviewers" erstellen (Read + Review)', completed: false },
      { id: 'rbac-1-4', title: 'External Collaborators Policy', completed: false },
    ],
  },
  {
    id: 'rbac-2',
    title: 'Infrastructure Access Control',
    description: 'Zugriffsrechte auf Server und Cloud-Ressourcen',
    category: 'rbac',
    priority: 'critical',
    status: 'not_started',
    subtasks: [
      { id: 'rbac-2-1', title: 'SSH Key Management Policy', completed: false },
      { id: 'rbac-2-2', title: 'Production Server Access Audit Log', completed: false },
      { id: 'rbac-2-3', title: 'Database Access nur ueber Jump Host', completed: false },
      { id: 'rbac-2-4', title: 'Secrets Management (Vault/AWS Secrets)', completed: false },
    ],
  },
  {
    id: 'rbac-3',
    title: 'Admin Panel Access Control',
    description: 'Rollenbasierte Zugriffsrechte im Admin Frontend',
    category: 'rbac',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'rbac-3-1', title: 'Admin Authentication implementieren', completed: false },
      { id: 'rbac-3-2', title: 'Role-based Views (Admin vs. Support)', completed: false },
      { id: 'rbac-3-3', title: 'Audit Log fuer Admin-Aktionen', completed: false },
    ],
  },

  // Git & Branch Protection
  {
    id: 'git-1',
    title: 'Protected Branches Setup',
    description: 'Schutz fuer main/develop Branches',
    category: 'git',
    priority: 'critical',
    status: 'not_started',
    subtasks: [
      { id: 'git-1-1', title: 'main Branch: No direct push', completed: false },
      { id: 'git-1-2', title: 'Require PR with min. 1 Approval', completed: false },
      { id: 'git-1-3', title: 'Require Status Checks (CI muss gruen sein)', completed: false },
      { id: 'git-1-4', title: 'Require Signed Commits', completed: false },
    ],
  },
  {
    id: 'git-2',
    title: 'Pull Request Template',
    description: 'Standardisierte PR-Beschreibung mit Checkliste',
    category: 'git',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'git-2-1', title: 'PR Template mit Description, Testing, Checklist', completed: false },
      { id: 'git-2-2', title: 'Issue Template fuer Bugs und Features', completed: false },
      { id: 'git-2-3', title: 'Automatische Labels basierend auf Aenderungen', completed: false },
    ],
  },
  {
    id: 'git-3',
    title: 'Code Review Guidelines',
    description: 'Dokumentierte Richtlinien fuer Code Reviews',
    category: 'git',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'git-3-1', title: 'Code Review Checklist erstellen', completed: false },
      { id: 'git-3-2', title: 'Review Turnaround Time Policy', completed: false },
      { id: 'git-3-3', title: 'CODEOWNERS Datei pflegen', completed: false },
    ],
  },

  // Release Management
  {
    id: 'rel-1',
    title: 'Semantic Versioning Setup',
    description: 'Automatische Versionierung nach SemVer',
    category: 'release',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'rel-1-1', title: 'Conventional Commits erzwingen', completed: false },
      { id: 'rel-1-2', title: 'semantic-release oder release-please einrichten', completed: false },
      { id: 'rel-1-3', title: 'Automatische Git Tags', completed: false },
    ],
  },
  {
    id: 'rel-2',
    title: 'Changelog Automation',
    description: 'Automatisch generierte Release Notes',
    category: 'release',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'rel-2-1', title: 'CHANGELOG.md automatisch generieren', completed: false },
      { id: 'rel-2-2', title: 'GitHub Release mit Notes erstellen', completed: false },
      { id: 'rel-2-3', title: 'Breaking Changes hervorheben', completed: false },
    ],
  },
  {
    id: 'rel-3',
    title: 'Release Branches Strategy',
    description: 'Branching-Modell fuer Releases definieren',
    category: 'release',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'rel-3-1', title: 'Git Flow oder GitHub Flow definieren', completed: false },
      { id: 'rel-3-2', title: 'Hotfix Branch Process', completed: false },
      { id: 'rel-3-3', title: 'Release Branch Protection', completed: false },
    ],
  },

  // Data Protection
  {
    id: 'data-1',
    title: 'Database Backup Strategy',
    description: 'Automatische Backups mit Retention Policy',
    category: 'data',
    priority: 'critical',
    status: 'not_started',
    subtasks: [
      { id: 'data-1-1', title: 'Taegliche automatische Backups', completed: false },
      { id: 'data-1-2', title: 'Point-in-Time Recovery aktivieren', completed: false },
      { id: 'data-1-3', title: 'Backup Encryption at Rest', completed: false },
      { id: 'data-1-4', title: 'Backup Restore Test dokumentieren', completed: false },
    ],
  },
  {
    id: 'data-2',
    title: 'Customer Data Protection',
    description: 'Schutz von Stammdaten, Consent & Dokumenten',
    category: 'data',
    priority: 'critical',
    status: 'not_started',
    subtasks: [
      { id: 'data-2-1', title: 'Stammdaten: Encryption at Rest', completed: false },
      { id: 'data-2-2', title: 'Consent-Daten: Audit Log fuer Aenderungen', completed: false },
      { id: 'data-2-3', title: 'Dokumente: Secure Storage (S3 mit Encryption)', completed: false },
      { id: 'data-2-4', title: 'PII Data Masking in Logs', completed: false },
    ],
  },
  {
    id: 'data-3',
    title: 'Migration Safety',
    description: 'Sichere Datenbank-Migrationen ohne Datenverlust',
    category: 'data',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'data-3-1', title: 'Migration Pre-Check Script', completed: false },
      { id: 'data-3-2', title: 'Rollback-faehige Migrationen', completed: false },
      { id: 'data-3-3', title: 'Staging Migration Test vor Production', completed: false },
    ],
  },
  {
    id: 'data-4',
    title: 'Data Anonymization',
    description: 'Anonymisierte Daten fuer Staging/Test',
    category: 'data',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'data-4-1', title: 'Anonymisierungs-Script fuer Staging DB', completed: false },
      { id: 'data-4-2', title: 'Test-Datengenerator', completed: false },
      { id: 'data-4-3', title: 'DSGVO-konforme Loeschung in Test-Systemen', completed: false },
    ],
  },

  // Compliance & SBOM
  {
    id: 'sbom-1',
    title: 'Software Bill of Materials (SBOM) erstellen',
    description: 'Vollstaendige Liste aller Open Source Komponenten',
    category: 'compliance',
    priority: 'high',
    status: 'completed',
    notes: 'Implementiert in /admin/sbom - 70+ Komponenten dokumentiert inkl. Docker Services, Security Tools, Python/Go/Node Packages',
    subtasks: [
      { id: 'sbom-1-1', title: 'Go Dependencies auflisten (go.mod)', completed: true },
      { id: 'sbom-1-2', title: 'Python Dependencies auflisten (requirements.txt)', completed: true },
      { id: 'sbom-1-3', title: 'npm Dependencies auflisten (package.json)', completed: true },
      { id: 'sbom-1-4', title: 'Docker Base Images dokumentieren', completed: true },
      { id: 'sbom-1-5', title: 'SBOM in CycloneDX/SPDX Format exportieren', completed: true },
    ],
  },
  {
    id: 'sbom-2',
    title: 'Open Source Lizenz-Compliance',
    description: 'Pruefung aller Lizenzen auf Kompatibilitaet',
    category: 'compliance',
    priority: 'high',
    status: 'in_progress',
    subtasks: [
      { id: 'sbom-2-1', title: 'Alle Lizenzen identifizieren (MIT, Apache, GPL, etc.)', completed: true },
      { id: 'sbom-2-2', title: 'Lizenz-Kompatibilitaet pruefen', completed: false },
      { id: 'sbom-2-3', title: 'LICENSES.md Datei erstellen', completed: false },
      { id: 'sbom-2-4', title: 'Third-Party Notices generieren', completed: false },
    ],
  },
  {
    id: 'sbom-3',
    title: 'Open Source Policy',
    description: 'Richtlinien fuer Verwendung von Open Source',
    category: 'compliance',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'sbom-3-1', title: 'Erlaubte Lizenzen definieren', completed: false },
      { id: 'sbom-3-2', title: 'Genehmigungsprozess fuer neue Dependencies', completed: false },
      { id: 'sbom-3-3', title: 'Automatische Lizenz-Checks in CI', completed: false },
    ],
  },
  {
    id: 'sbom-4',
    title: 'Aktuelle Open Source Komponenten dokumentieren',
    description: 'BreakPilot Open Source Stack dokumentieren',
    category: 'compliance',
    priority: 'medium',
    status: 'completed',
    notes: 'Implementiert in /admin/sbom und /admin/architecture - 32 Docker Services, 14 Security Tools, 26+ Libraries',
    subtasks: [
      { id: 'sbom-4-1', title: 'Backend: FastAPI, Pydantic, httpx, anthropic', completed: true },
      { id: 'sbom-4-2', title: 'Go Services: Gin, GORM, goquery', completed: true },
      { id: 'sbom-4-3', title: 'Frontend: Next.js, React, Tailwind', completed: true },
      { id: 'sbom-4-4', title: 'Infrastructure: PostgreSQL, OpenSearch, Ollama', completed: true },
    ],
  },

  // Approval Workflow
  {
    id: 'appr-1',
    title: 'Release Approval Gates',
    description: 'Mehrstufige Freigabe vor Production Deploy',
    category: 'approval',
    priority: 'critical',
    status: 'not_started',
    subtasks: [
      { id: 'appr-1-1', title: 'QA Sign-off erforderlich', completed: false },
      { id: 'appr-1-2', title: 'Security Review fuer kritische Aenderungen', completed: false },
      { id: 'appr-1-3', title: 'Product Owner Freigabe', completed: false },
      { id: 'appr-1-4', title: 'GitHub Environments mit Required Reviewers', completed: false },
    ],
  },
  {
    id: 'appr-2',
    title: 'Deployment Windows',
    description: 'Definierte Zeitfenster fuer Production Deployments',
    category: 'approval',
    priority: 'medium',
    status: 'not_started',
    subtasks: [
      { id: 'appr-2-1', title: 'Deployment-Kalender definieren', completed: false },
      { id: 'appr-2-2', title: 'Freeze Periods (z.B. vor Feiertagen)', completed: false },
      { id: 'appr-2-3', title: 'Emergency Hotfix Process', completed: false },
    ],
  },
  {
    id: 'appr-3',
    title: 'Post-Deployment Verification',
    description: 'Checks nach erfolgreichem Deployment',
    category: 'approval',
    priority: 'high',
    status: 'not_started',
    subtasks: [
      { id: 'appr-3-1', title: 'Smoke Tests automatisieren', completed: false },
      { id: 'appr-3-2', title: 'Error Rate Monitoring (erste 30 Min)', completed: false },
      { id: 'appr-3-3', title: 'Rollback-Kriterien definieren', completed: false },
    ],
  },
]

const statusLabels: Record<BacklogItem['status'], { label: string; color: string }> = {
  not_started: { label: 'Nicht begonnen', color: 'bg-slate-100 text-slate-600' },
  in_progress: { label: 'In Arbeit', color: 'bg-blue-100 text-blue-700' },
  review: { label: 'In Review', color: 'bg-yellow-100 text-yellow-700' },
  completed: { label: 'Abgeschlossen', color: 'bg-green-100 text-green-700' },
  blocked: { label: 'Blockiert', color: 'bg-red-100 text-red-700' },
}

const priorityLabels: Record<BacklogItem['priority'], { label: string; color: string }> = {
  critical: { label: 'Kritisch', color: 'bg-red-500 text-white' },
  high: { label: 'Hoch', color: 'bg-orange-500 text-white' },
  medium: { label: 'Mittel', color: 'bg-yellow-500 text-white' },
  low: { label: 'Niedrig', color: 'bg-slate-500 text-white' },
}

export default function BacklogPage() {
  const [items, setItems] = useState<BacklogItem[]>(initialBacklogItems)
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const [selectedPriority, setSelectedPriority] = useState<string | null>(null)
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set())
  const [searchQuery, setSearchQuery] = useState('')

  // Load saved state from localStorage
  useEffect(() => {
    const saved = localStorage.getItem('backlogItems')
    if (saved) {
      try {
        setItems(JSON.parse(saved))
      } catch (e) {
        console.error('Failed to load backlog items:', e)
      }
    }
  }, [])

  // Save state to localStorage
  useEffect(() => {
    localStorage.setItem('backlogItems', JSON.stringify(items))
  }, [items])

  const filteredItems = items.filter((item) => {
    if (selectedCategory && item.category !== selectedCategory) return false
    if (selectedPriority && item.priority !== selectedPriority) return false
    if (searchQuery) {
      const query = searchQuery.toLowerCase()
      return (
        item.title.toLowerCase().includes(query) ||
        item.description.toLowerCase().includes(query) ||
        item.subtasks?.some((st) => st.title.toLowerCase().includes(query))
      )
    }
    return true
  })

  const toggleExpand = (id: string) => {
    const newExpanded = new Set(expandedItems)
    if (newExpanded.has(id)) {
      newExpanded.delete(id)
    } else {
      newExpanded.add(id)
    }
    setExpandedItems(newExpanded)
  }

  const updateItemStatus = (id: string, status: BacklogItem['status']) => {
    setItems(items.map((item) => (item.id === id ? { ...item, status } : item)))
  }

  const toggleSubtask = (itemId: string, subtaskId: string) => {
    setItems(
      items.map((item) => {
        if (item.id !== itemId) return item
        return {
          ...item,
          subtasks: item.subtasks?.map((st) =>
            st.id === subtaskId ? { ...st, completed: !st.completed } : st
          ),
        }
      })
    )
  }

  const getProgress = () => {
    const total = items.length
    const completed = items.filter((i) => i.status === 'completed').length
    return { total, completed, percentage: Math.round((completed / total) * 100) }
  }

  const getCategoryProgress = (categoryId: string) => {
    const categoryItems = items.filter((i) => i.category === categoryId)
    const completed = categoryItems.filter((i) => i.status === 'completed').length
    return { total: categoryItems.length, completed }
  }

  const progress = getProgress()

  return (
    <AdminLayout
      title="Production Readiness Backlog"
      description="Alle Aufgaben vor dem Go-Live"
    >
      {/* Overall Progress */}
      <div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">Gesamtfortschritt</h2>
            <p className="text-sm text-slate-500">
              {progress.completed} von {progress.total} Aufgaben abgeschlossen
            </p>
          </div>
          <div className="text-3xl font-bold text-primary-600">{progress.percentage}%</div>
        </div>
        <div className="w-full bg-slate-200 rounded-full h-3">
          <div
            className="bg-primary-600 h-3 rounded-full transition-all duration-500"
            style={{ width: `${progress.percentage}%` }}
          />
        </div>
      </div>

      {/* Category Cards */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-6">
        {categories.map((cat) => {
          const catProgress = getCategoryProgress(cat.id)
          return (
            <button
              key={cat.id}
              onClick={() => setSelectedCategory(selectedCategory === cat.id ? null : cat.id)}
              className={`p-4 rounded-xl border-2 text-left transition-all ${
                selectedCategory === cat.id
                  ? `${cat.color} ring-2 ring-offset-2`
                  : 'bg-white border-slate-200 hover:border-slate-300'
              }`}
            >
              <div className="flex items-center gap-3 mb-2">
                <span className={selectedCategory === cat.id ? '' : 'text-slate-600'}>
                  {cat.icon}
                </span>
                <span className="font-medium text-sm">{cat.name}</span>
              </div>
              <div className="text-xs text-slate-500">
                {catProgress.completed}/{catProgress.total} erledigt
              </div>
            </button>
          )
        })}
      </div>

      {/* Filters & Search */}
      <div className="flex flex-wrap gap-4 mb-6">
        <div className="flex-1 min-w-[200px]">
          <input
            type="text"
            placeholder="Suchen..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
          />
        </div>
        <select
          value={selectedPriority || ''}
          onChange={(e) => setSelectedPriority(e.target.value || null)}
          className="px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
        >
          <option value="">Alle Prioritaeten</option>
          <option value="critical">Kritisch</option>
          <option value="high">Hoch</option>
          <option value="medium">Mittel</option>
          <option value="low">Niedrig</option>
        </select>
        {(selectedCategory || selectedPriority || searchQuery) && (
          <button
            onClick={() => {
              setSelectedCategory(null)
              setSelectedPriority(null)
              setSearchQuery('')
            }}
            className="px-4 py-2 text-sm text-slate-600 hover:text-slate-900"
          >
            Filter zuruecksetzen
          </button>
        )}
      </div>

      {/* Backlog Items */}
      <div className="space-y-4">
        {filteredItems.map((item) => {
          const category = categories.find((c) => c.id === item.category)
          const isExpanded = expandedItems.has(item.id)
          const completedSubtasks = item.subtasks?.filter((st) => st.completed).length || 0
          const totalSubtasks = item.subtasks?.length || 0

          return (
            <div
              key={item.id}
              className="bg-white rounded-xl border border-slate-200 overflow-hidden"
            >
              <div
                className="p-4 cursor-pointer hover:bg-slate-50 transition-colors"
                onClick={() => toggleExpand(item.id)}
              >
                <div className="flex items-start gap-4">
                  {/* Expand Icon */}
                  <button className="mt-1 text-slate-400">
                    <svg
                      className={`w-5 h-5 transition-transform ${isExpanded ? 'rotate-90' : ''}`}
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M9 5l7 7-7 7"
                      />
                    </svg>
                  </button>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-1">
                      <h3 className="font-semibold text-slate-900 truncate">{item.title}</h3>
                      <span
                        className={`px-2 py-0.5 rounded text-xs font-medium ${
                          priorityLabels[item.priority].color
                        }`}
                      >
                        {priorityLabels[item.priority].label}
                      </span>
                    </div>
                    <p className="text-sm text-slate-500 mb-2">{item.description}</p>
                    <div className="flex items-center gap-4 text-xs">
                      <span className={`px-2 py-1 rounded border ${category?.color}`}>
                        {category?.name}
                      </span>
                      {totalSubtasks > 0 && (
                        <span className="text-slate-500">
                          {completedSubtasks}/{totalSubtasks} Teilaufgaben
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Status */}
                  <select
                    value={item.status}
                    onChange={(e) => {
                      e.stopPropagation()
                      updateItemStatus(item.id, e.target.value as BacklogItem['status'])
                    }}
                    onClick={(e) => e.stopPropagation()}
                    className={`px-3 py-1.5 rounded-lg text-sm font-medium border-0 cursor-pointer ${
                      statusLabels[item.status].color
                    }`}
                  >
                    {Object.entries(statusLabels).map(([value, { label }]) => (
                      <option key={value} value={value}>
                        {label}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Progress Bar for subtasks */}
                {totalSubtasks > 0 && (
                  <div className="mt-3 ml-9">
                    <div className="w-full bg-slate-200 rounded-full h-1.5">
                      <div
                        className="bg-green-500 h-1.5 rounded-full transition-all"
                        style={{ width: `${(completedSubtasks / totalSubtasks) * 100}%` }}
                      />
                    </div>
                  </div>
                )}
              </div>

              {/* Expanded Subtasks */}
              {isExpanded && item.subtasks && item.subtasks.length > 0 && (
                <div className="border-t border-slate-200 bg-slate-50 p-4 pl-14">
                  <h4 className="text-sm font-medium text-slate-700 mb-3">Teilaufgaben</h4>
                  <ul className="space-y-2">
                    {item.subtasks.map((subtask) => (
                      <li key={subtask.id} className="flex items-center gap-3">
                        <input
                          type="checkbox"
                          checked={subtask.completed}
                          onChange={() => toggleSubtask(item.id, subtask.id)}
                          className="w-4 h-4 rounded border-slate-300 text-primary-600 focus:ring-primary-500"
                        />
                        <span
                          className={`text-sm ${
                            subtask.completed ? 'text-slate-400 line-through' : 'text-slate-700'
                          }`}
                        >
                          {subtask.title}
                        </span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )
        })}
      </div>

      {filteredItems.length === 0 && (
        <div className="text-center py-12 text-slate-500">
          Keine Aufgaben gefunden. Versuche einen anderen Filter.
        </div>
      )}

      {/* Info Box */}
      <div className="mt-8 bg-amber-50 border border-amber-200 rounded-xl p-6">
        <div className="flex items-start gap-4">
          <svg
            className="w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
            />
          </svg>
          <div>
            <h3 className="font-semibold text-amber-900">Wichtiger Hinweis</h3>
            <p className="text-sm text-amber-800 mt-1">
              Diese Backlog-Liste muss vollstaendig abgearbeitet sein, bevor BreakPilot in den
              Produktivbetrieb gehen kann. Alle kritischen Items muessen abgeschlossen sein.
              Der Fortschritt wird lokal im Browser gespeichert.
            </p>
          </div>
        </div>
      </div>
    </AdminLayout>
  )
}
