'use client'

import React, { useState, useEffect, useCallback, useRef } from 'react'
import { useSDK } from '@/lib/sdk'

// =============================================================================
// TYPES
// =============================================================================

interface Roadmap {
  id: string
  title: string
  description: string
  version: number
  status: 'draft' | 'active' | 'completed' | 'archived'
  assessment_id: string | null
  portfolio_id: string | null
  total_items: number
  completed_items: number
  progress: number
  start_date: string | null
  target_date: string | null
  created_at: string
  updated_at: string
}

interface RoadmapItem {
  id: string
  roadmap_id: string
  title: string
  description: string
  category: 'TECHNICAL' | 'ORGANIZATIONAL' | 'PROCESSUAL' | 'DOCUMENTATION' | 'TRAINING'
  priority: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW'
  status: 'PLANNED' | 'IN_PROGRESS' | 'BLOCKED' | 'COMPLETED' | 'DEFERRED'
  control_id: string | null
  regulation_ref: string | null
  effort_days: number
  effort_hours: number
  estimated_cost: number
  assignee_name: string
  department: string
  planned_start: string | null
  planned_end: string | null
  actual_start: string | null
  actual_end: string | null
  evidence_required: boolean
  evidence_provided: boolean
  sort_order: number
  created_at: string
  updated_at: string
}

interface RoadmapStats {
  by_status: Record<string, number>
  by_priority: Record<string, number>
  by_category: Record<string, number>
  by_department: Record<string, number>
  overdue_items: number
  upcoming_items: number
  total_effort_days: number
  progress: number
}

interface ImportJob {
  id: string
  status: 'pending' | 'parsing' | 'validating' | 'completed' | 'failed'
  filename: string
  total_rows: number
  valid_rows: number
  invalid_rows: number
  items: ParsedItem[]
}

interface ParsedItem {
  row: number
  title: string
  description: string
  category: string
  priority: string
  is_valid: boolean
  errors: string[]
  warnings: string[]
  matched_control: string | null
  match_confidence: number
}

// =============================================================================
// API
// =============================================================================

const API_BASE = '/api/sdk/v1/roadmap'

async function api<T>(path: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: res.statusText }))
    throw new Error(err.error || err.message || `HTTP ${res.status}`)
  }
  return res.json()
}

// =============================================================================
// COMPONENTS
// =============================================================================

const statusColors: Record<string, string> = {
  draft: 'bg-gray-100 text-gray-700',
  active: 'bg-green-100 text-green-700',
  completed: 'bg-purple-100 text-purple-700',
  archived: 'bg-red-100 text-red-700',
}

const statusLabels: Record<string, string> = {
  draft: 'Entwurf',
  active: 'Aktiv',
  completed: 'Abgeschlossen',
  archived: 'Archiviert',
}

const itemStatusColors: Record<string, string> = {
  PLANNED: 'bg-gray-100 text-gray-700',
  IN_PROGRESS: 'bg-blue-100 text-blue-700',
  BLOCKED: 'bg-red-100 text-red-700',
  COMPLETED: 'bg-green-100 text-green-700',
  DEFERRED: 'bg-yellow-100 text-yellow-700',
}

const itemStatusLabels: Record<string, string> = {
  PLANNED: 'Geplant',
  IN_PROGRESS: 'In Arbeit',
  BLOCKED: 'Blockiert',
  COMPLETED: 'Erledigt',
  DEFERRED: 'Verschoben',
}

const priorityColors: Record<string, string> = {
  CRITICAL: 'bg-red-100 text-red-700',
  HIGH: 'bg-orange-100 text-orange-700',
  MEDIUM: 'bg-yellow-100 text-yellow-700',
  LOW: 'bg-green-100 text-green-700',
}

const categoryLabels: Record<string, string> = {
  TECHNICAL: 'Technisch',
  ORGANIZATIONAL: 'Organisatorisch',
  PROCESSUAL: 'Prozessual',
  DOCUMENTATION: 'Dokumentation',
  TRAINING: 'Schulung',
}

function RoadmapCard({ roadmap, onSelect, onDelete }: {
  roadmap: Roadmap
  onSelect: (r: Roadmap) => void
  onDelete: (id: string) => void
}) {
  return (
    <div className="bg-white rounded-xl border-2 border-gray-200 p-6 hover:border-purple-300 transition-colors cursor-pointer"
      onClick={() => onSelect(roadmap)}>
      <div className="flex items-start justify-between mb-3">
        <h4 className="font-semibold text-gray-900 truncate flex-1">{roadmap.title}</h4>
        <span className={`px-2 py-1 text-xs rounded-full ml-2 ${statusColors[roadmap.status] || 'bg-gray-100 text-gray-700'}`}>
          {statusLabels[roadmap.status] || roadmap.status}
        </span>
      </div>
      {roadmap.description && (
        <p className="text-sm text-gray-600 mb-3 line-clamp-2">{roadmap.description}</p>
      )}

      <div className="mb-3">
        <div className="flex justify-between text-xs text-gray-500 mb-1">
          <span>{roadmap.completed_items}/{roadmap.total_items} Items</span>
          <span>{roadmap.progress}%</span>
        </div>
        <div className="w-full h-2 bg-gray-100 rounded-full overflow-hidden">
          <div className="h-full bg-purple-500 rounded-full transition-all" style={{ width: `${roadmap.progress}%` }} />
        </div>
      </div>

      {(roadmap.start_date || roadmap.target_date) && (
        <div className="flex items-center gap-2 text-xs text-gray-500 mb-3">
          {roadmap.start_date && <span>Start: {new Date(roadmap.start_date).toLocaleDateString('de-DE')}</span>}
          {roadmap.target_date && <span>Ziel: {new Date(roadmap.target_date).toLocaleDateString('de-DE')}</span>}
        </div>
      )}

      <div className="flex justify-between items-center">
        <span className="text-xs text-gray-400">v{roadmap.version}</span>
        <button onClick={(e) => { e.stopPropagation(); onDelete(roadmap.id) }}
          className="text-xs text-red-500 hover:text-red-700 hover:bg-red-50 px-2 py-1 rounded">
          Loeschen
        </button>
      </div>
    </div>
  )
}

function CreateRoadmapModal({ onClose, onCreated }: {
  onClose: () => void
  onCreated: () => void
}) {
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [startDate, setStartDate] = useState('')
  const [targetDate, setTargetDate] = useState('')
  const [saving, setSaving] = useState(false)

  const handleCreate = async () => {
    if (!title.trim()) return
    setSaving(true)
    try {
      await api('', {
        method: 'POST',
        body: JSON.stringify({
          title: title.trim(),
          description: description.trim(),
          start_date: startDate || null,
          target_date: targetDate || null,
        }),
      })
      onCreated()
    } catch (err) {
      console.error('Create roadmap error:', err)
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
      <div className="bg-white rounded-2xl p-6 w-full max-w-lg" onClick={e => e.stopPropagation()}>
        <h3 className="text-lg font-bold text-gray-900 mb-4">Neue Roadmap</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
            <input type="text" value={title} onChange={e => setTitle(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              placeholder="z.B. AI Act Compliance Roadmap" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
            <textarea value={description} onChange={e => setDescription(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              rows={3} />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Startdatum</label>
              <input type="date" value={startDate} onChange={e => setStartDate(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Zieldatum</label>
              <input type="date" value={targetDate} onChange={e => setTargetDate(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
            </div>
          </div>
        </div>
        <div className="flex justify-end gap-3 mt-6">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
          <button onClick={handleCreate} disabled={!title.trim() || saving}
            className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
            {saving ? 'Erstelle...' : 'Erstellen'}
          </button>
        </div>
      </div>
    </div>
  )
}

function CreateItemModal({ roadmapId, onClose, onCreated }: {
  roadmapId: string
  onClose: () => void
  onCreated: () => void
}) {
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [category, setCategory] = useState<string>('TECHNICAL')
  const [priority, setPriority] = useState<string>('MEDIUM')
  const [assigneeName, setAssigneeName] = useState('')
  const [department, setDepartment] = useState('')
  const [effortDays, setEffortDays] = useState(1)
  const [saving, setSaving] = useState(false)

  const handleCreate = async () => {
    if (!title.trim()) return
    setSaving(true)
    try {
      await api(`/${roadmapId}/items`, {
        method: 'POST',
        body: JSON.stringify({
          title: title.trim(),
          description: description.trim(),
          category,
          priority,
          assignee_name: assigneeName.trim(),
          department: department.trim(),
          effort_days: effortDays,
        }),
      })
      onCreated()
    } catch (err) {
      console.error('Create item error:', err)
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
      <div className="bg-white rounded-2xl p-6 w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <h3 className="text-lg font-bold text-gray-900 mb-4">Neues Item</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
            <input type="text" value={title} onChange={e => setTitle(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
            <textarea value={description} onChange={e => setDescription(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" rows={2} />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
              <select value={category} onChange={e => setCategory(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                {Object.entries(categoryLabels).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Prioritaet</label>
              <select value={priority} onChange={e => setPriority(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                <option value="CRITICAL">Kritisch</option>
                <option value="HIGH">Hoch</option>
                <option value="MEDIUM">Mittel</option>
                <option value="LOW">Niedrig</option>
              </select>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Zustaendig</label>
              <input type="text" value={assigneeName} onChange={e => setAssigneeName(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Abteilung</label>
              <input type="text" value={department} onChange={e => setDepartment(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Aufwand (Tage)</label>
              <input type="number" value={effortDays} onChange={e => setEffortDays(Number(e.target.value))}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" min={0} />
            </div>
          </div>
        </div>
        <div className="flex justify-end gap-3 mt-6">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
          <button onClick={handleCreate} disabled={!title.trim() || saving}
            className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
            {saving ? 'Erstelle...' : 'Erstellen'}
          </button>
        </div>
      </div>
    </div>
  )
}

function ImportWizard({ onClose, onImported }: {
  onClose: () => void
  onImported: () => void
}) {
  const [step, setStep] = useState<'upload' | 'preview' | 'confirm'>('upload')
  const [importJob, setImportJob] = useState<ImportJob | null>(null)
  const [uploading, setUploading] = useState(false)
  const [confirming, setConfirming] = useState(false)
  const [roadmapTitle, setRoadmapTitle] = useState('')
  const fileRef = useRef<HTMLInputElement>(null)

  const handleUpload = async () => {
    const file = fileRef.current?.files?.[0]
    if (!file) return
    setUploading(true)
    try {
      const formData = new FormData()
      formData.append('file', file)
      const res = await fetch(`${API_BASE}/import/upload`, {
        method: 'POST',
        body: formData,
      })
      if (!res.ok) throw new Error(`Upload failed: ${res.status}`)
      const data = await res.json()

      // Fetch parsed job
      const job = await api<ImportJob>(`/import/${data.job_id || data.id}`)
      setImportJob(job)
      setStep('preview')
    } catch (err) {
      console.error('Upload error:', err)
    } finally {
      setUploading(false)
    }
  }

  const handleConfirm = async () => {
    if (!importJob) return
    setConfirming(true)
    try {
      await api(`/import/${importJob.id}/confirm`, {
        method: 'POST',
        body: JSON.stringify({
          job_id: importJob.id,
          roadmap_title: roadmapTitle || `Import ${new Date().toLocaleDateString('de-DE')}`,
          selected_rows: importJob.items.filter(i => i.is_valid).map(i => i.row),
          apply_mappings: true,
        }),
      })
      onImported()
    } catch (err) {
      console.error('Confirm error:', err)
    } finally {
      setConfirming(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
      <div className="bg-white rounded-2xl p-6 w-full max-w-2xl max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <h3 className="text-lg font-bold text-gray-900 mb-4">Roadmap importieren</h3>

        {step === 'upload' && (
          <div className="space-y-4">
            <div className="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center">
              <input ref={fileRef} type="file" accept=".xlsx,.xls,.csv" className="hidden" onChange={() => {}} />
              <svg className="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
              </svg>
              <button onClick={() => fileRef.current?.click()}
                className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700">
                Datei auswaehlen
              </button>
              <p className="text-xs text-gray-500 mt-2">Excel (.xlsx, .xls) oder CSV</p>
            </div>
            <div className="flex justify-end gap-3">
              <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
              <button onClick={handleUpload} disabled={uploading || !fileRef.current?.files?.length}
                className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
                {uploading ? 'Lade hoch...' : 'Hochladen'}
              </button>
            </div>
          </div>
        )}

        {step === 'preview' && importJob && (
          <div className="space-y-4">
            <div className="grid grid-cols-3 gap-3">
              <div className="bg-green-50 rounded-lg p-3 text-center">
                <div className="text-xl font-bold text-green-600">{importJob.valid_rows}</div>
                <div className="text-xs text-gray-500">Gueltig</div>
              </div>
              <div className="bg-red-50 rounded-lg p-3 text-center">
                <div className="text-xl font-bold text-red-600">{importJob.invalid_rows}</div>
                <div className="text-xs text-gray-500">Ungueltig</div>
              </div>
              <div className="bg-gray-50 rounded-lg p-3 text-center">
                <div className="text-xl font-bold text-gray-900">{importJob.total_rows}</div>
                <div className="text-xs text-gray-500">Gesamt</div>
              </div>
            </div>

            <div className="max-h-64 overflow-y-auto border rounded-lg">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 sticky top-0">
                  <tr>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Zeile</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Titel</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Kategorie</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {importJob.items?.map(item => (
                    <tr key={item.row} className={item.is_valid ? '' : 'bg-red-50'}>
                      <td className="px-3 py-2 text-gray-500">{item.row}</td>
                      <td className="px-3 py-2 text-gray-900">{item.title}</td>
                      <td className="px-3 py-2 text-gray-600">{item.category}</td>
                      <td className="px-3 py-2">
                        {item.is_valid ? (
                          <span className="text-green-600 text-xs">OK</span>
                        ) : (
                          <span className="text-red-600 text-xs">{item.errors?.join(', ')}</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Roadmap-Titel</label>
              <input type="text" value={roadmapTitle} onChange={e => setRoadmapTitle(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500"
                placeholder="Name fuer die importierte Roadmap" />
            </div>

            <div className="flex justify-end gap-3">
              <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
              <button onClick={handleConfirm} disabled={confirming || importJob.valid_rows === 0}
                className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
                {confirming ? 'Importiere...' : `${importJob.valid_rows} Items importieren`}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

function RoadmapDetailView({ roadmap, onBack, onRefresh }: {
  roadmap: Roadmap
  onBack: () => void
  onRefresh: () => void
}) {
  const [items, setItems] = useState<RoadmapItem[]>([])
  const [stats, setStats] = useState<RoadmapStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [showCreateItem, setShowCreateItem] = useState(false)
  const [filterStatus, setFilterStatus] = useState<string>('all')
  const [filterPriority, setFilterPriority] = useState<string>('all')

  const loadDetails = useCallback(async () => {
    setLoading(true)
    try {
      const [i, s] = await Promise.all([
        api<RoadmapItem[] | { items: RoadmapItem[] }>(`/${roadmap.id}/items`).catch(() => []),
        api<RoadmapStats>(`/${roadmap.id}/stats`).catch(() => null),
      ])
      const itemList = Array.isArray(i) ? i : ((i as { items: RoadmapItem[] }).items || [])
      setItems(itemList)
      setStats(s)
    } finally {
      setLoading(false)
    }
  }, [roadmap.id])

  useEffect(() => { loadDetails() }, [loadDetails])

  const handleStatusChange = async (itemId: string, newStatus: string) => {
    try {
      // roadmap-items is a separate route group in Go backend
      const res = await fetch(`/api/sdk/v1/roadmap-items/${itemId}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      })
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      loadDetails()
    } catch (err) {
      console.error('Status change error:', err)
    }
  }

  const handleDeleteItem = async (itemId: string) => {
    try {
      const res = await fetch(`/api/sdk/v1/roadmap-items/${itemId}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
      })
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      setItems(prev => prev.filter(i => i.id !== itemId))
    } catch (err) {
      console.error('Delete item error:', err)
    }
  }

  const filteredItems = items.filter(i => {
    if (filterStatus !== 'all' && i.status !== filterStatus) return false
    if (filterPriority !== 'all' && i.priority !== filterPriority) return false
    return true
  })

  return (
    <div>
      <button onClick={onBack} className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        Zurueck zur Uebersicht
      </button>

      <div className="bg-white rounded-xl border-2 border-gray-200 p-6 mb-6">
        <div className="flex items-start justify-between mb-4">
          <div>
            <h2 className="text-xl font-bold text-gray-900">{roadmap.title}</h2>
            <p className="text-sm text-gray-500 mt-1">{roadmap.description}</p>
          </div>
          <span className={`px-3 py-1 text-sm rounded-full ${statusColors[roadmap.status]}`}>
            {statusLabels[roadmap.status]}
          </span>
        </div>

        <div className="mb-4">
          <div className="flex justify-between text-sm text-gray-500 mb-1">
            <span>{roadmap.completed_items}/{roadmap.total_items} Items abgeschlossen</span>
            <span>{roadmap.progress}%</span>
          </div>
          <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
            <div className="h-full bg-purple-500 rounded-full transition-all" style={{ width: `${roadmap.progress}%` }} />
          </div>
        </div>

        {stats && (
          <div className="grid grid-cols-4 gap-4 mb-4">
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-red-600">{stats.overdue_items}</div>
              <div className="text-xs text-gray-500">Ueberfaellig</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-yellow-600">{stats.upcoming_items}</div>
              <div className="text-xs text-gray-500">Anstehend</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-gray-900">{stats.total_effort_days}</div>
              <div className="text-xs text-gray-500">Aufwand (Tage)</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-purple-600">{stats.progress}%</div>
              <div className="text-xs text-gray-500">Fortschritt</div>
            </div>
          </div>
        )}

        <button onClick={() => setShowCreateItem(true)}
          className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700">
          Neues Item
        </button>
      </div>

      {/* Filters */}
      <div className="flex gap-4 mb-4">
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-500">Status:</span>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
            className="px-2 py-1 text-sm border rounded-lg">
            <option value="all">Alle</option>
            {Object.entries(itemStatusLabels).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-500">Prioritaet:</span>
          <select value={filterPriority} onChange={e => setFilterPriority(e.target.value)}
            className="px-2 py-1 text-sm border rounded-lg">
            <option value="all">Alle</option>
            <option value="CRITICAL">Kritisch</option>
            <option value="HIGH">Hoch</option>
            <option value="MEDIUM">Mittel</option>
            <option value="LOW">Niedrig</option>
          </select>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-8 text-gray-500">Laden...</div>
      ) : (
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Titel</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kategorie</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Prioritaet</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Zustaendig</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aufwand</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aktion</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filteredItems.map(item => (
                <tr key={item.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3">
                    <div className="font-medium text-gray-900">{item.title}</div>
                    {item.regulation_ref && <div className="text-xs text-gray-500">{item.regulation_ref}</div>}
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">
                    {categoryLabels[item.category] || item.category}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 text-xs rounded-full ${priorityColors[item.priority] || 'bg-gray-100 text-gray-700'}`}>
                      {item.priority}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <select
                      value={item.status}
                      onChange={e => handleStatusChange(item.id, e.target.value)}
                      className={`px-2 py-0.5 text-xs rounded-full border-0 ${itemStatusColors[item.status] || 'bg-gray-100 text-gray-700'}`}
                    >
                      {Object.entries(itemStatusLabels).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                    </select>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">
                    {item.assignee_name || '-'}
                    {item.department && <div className="text-xs text-gray-400">{item.department}</div>}
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">{item.effort_days}d</td>
                  <td className="px-4 py-3">
                    <button onClick={() => handleDeleteItem(item.id)}
                      className="text-xs text-red-500 hover:text-red-700">Loeschen</button>
                  </td>
                </tr>
              ))}
              {filteredItems.length === 0 && (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-500">Keine Items</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {showCreateItem && (
        <CreateItemModal roadmapId={roadmap.id} onClose={() => setShowCreateItem(false)}
          onCreated={() => { setShowCreateItem(false); loadDetails(); onRefresh() }} />
      )}
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function RoadmapPage() {
  const { setCurrentModule } = useSDK()
  const [roadmaps, setRoadmaps] = useState<Roadmap[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [showImport, setShowImport] = useState(false)
  const [selectedRoadmap, setSelectedRoadmap] = useState<Roadmap | null>(null)
  const [filter, setFilter] = useState<string>('all')

  useEffect(() => {
    setCurrentModule('roadmap')
  }, [setCurrentModule])

  const loadRoadmaps = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api<Roadmap[] | { roadmaps: Roadmap[] }>('')
      const list = Array.isArray(data) ? data : (data.roadmaps || [])
      setRoadmaps(list)
    } catch (err) {
      console.error('Load roadmaps error:', err)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { loadRoadmaps() }, [loadRoadmaps])

  const handleDelete = async (id: string) => {
    if (!confirm('Roadmap wirklich loeschen?')) return
    try {
      await api(`/${id}`, { method: 'DELETE' })
      setRoadmaps(prev => prev.filter(r => r.id !== id))
    } catch (err) {
      console.error('Delete error:', err)
    }
  }

  const filteredRoadmaps = filter === 'all'
    ? roadmaps
    : roadmaps.filter(r => r.status === filter)

  if (selectedRoadmap) {
    return (
      <div className="p-6 max-w-6xl mx-auto">
        <RoadmapDetailView
          roadmap={selectedRoadmap}
          onBack={() => { setSelectedRoadmap(null); loadRoadmaps() }}
          onRefresh={() => {
            loadRoadmaps().then(() => {
              const updated = roadmaps.find(r => r.id === selectedRoadmap.id)
              if (updated) setSelectedRoadmap(updated)
            })
          }}
        />
      </div>
    )
  }

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Compliance Roadmaps</h1>
          <p className="text-sm text-gray-500 mt-1">
            Umsetzungsplaene fuer Compliance-Massnahmen
          </p>
        </div>
        <div className="flex gap-2">
          <button onClick={() => setShowImport(true)}
            className="px-4 py-2 border border-gray-300 text-gray-700 text-sm rounded-lg hover:bg-gray-50 flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            Importieren
          </button>
          <button onClick={() => setShowCreate(true)}
            className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            Neue Roadmap
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[
          { label: 'Gesamt', value: roadmaps.length, color: 'text-gray-900' },
          { label: 'Aktiv', value: roadmaps.filter(r => r.status === 'active').length, color: 'text-green-600' },
          { label: 'Entwurf', value: roadmaps.filter(r => r.status === 'draft').length, color: 'text-gray-600' },
          { label: 'Abgeschlossen', value: roadmaps.filter(r => r.status === 'completed').length, color: 'text-purple-600' },
        ].map(stat => (
          <div key={stat.label} className="bg-white rounded-xl border border-gray-200 p-4 text-center">
            <div className={`text-2xl font-bold ${stat.color}`}>{stat.value}</div>
            <div className="text-xs text-gray-500">{stat.label}</div>
          </div>
        ))}
      </div>

      {/* Filter */}
      <div className="flex gap-2 mb-6">
        {['all', 'draft', 'active', 'completed'].map(f => (
          <button key={f} onClick={() => setFilter(f)}
            className={`px-3 py-1.5 text-sm rounded-lg ${filter === f ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
            {f === 'all' ? 'Alle' : statusLabels[f] || f}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">Roadmaps werden geladen...</div>
      ) : filteredRoadmaps.length === 0 ? (
        <div className="text-center py-12">
          <div className="text-gray-400 mb-2">
            <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
            </svg>
          </div>
          <p className="text-gray-500">Keine Roadmaps gefunden</p>
          <button onClick={() => setShowCreate(true)} className="mt-3 text-sm text-purple-600 hover:text-purple-700">
            Erste Roadmap erstellen
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredRoadmaps.map(r => (
            <RoadmapCard key={r.id} roadmap={r} onSelect={setSelectedRoadmap} onDelete={handleDelete} />
          ))}
        </div>
      )}

      {showCreate && (
        <CreateRoadmapModal onClose={() => setShowCreate(false)} onCreated={() => { setShowCreate(false); loadRoadmaps() }} />
      )}
      {showImport && (
        <ImportWizard onClose={() => setShowImport(false)} onImported={() => { setShowImport(false); loadRoadmaps() }} />
      )}
    </div>
  )
}
