'use client'

import React, { useState } from 'react'
import { SecurityItemCard } from './_components/SecurityItemCard'
import { ItemModal } from './_components/ItemModal'
import { useSecurityBacklog, EMPTY_NEW_ITEM } from './_hooks/useSecurityBacklog'
import type { SecurityItem } from './_hooks/useSecurityBacklog'
import { LicenseModuleBanner } from '@/components/sdk/LicenseModuleBanner'

export default function SecurityBacklogPage() {
  const [filter, setFilter] = useState<string>('all')
  const [showModal, setShowModal] = useState(false)
  const [editItem, setEditItem] = useState<SecurityItem | null>(null)

  const {
    items,
    stats,
    loading,
    handleCreate,
    handleUpdate,
    handleDelete,
    handleStatusChange,
  } = useSecurityBacklog()

  const filteredItems = filter === 'all'
    ? items
    : items.filter(i => i.severity === filter || i.status === filter || i.type === filter)

  async function onSave(form: Parameters<typeof handleCreate>[0]) {
    if (editItem) {
      const ok = await handleUpdate(editItem.id, form)
      if (ok) setEditItem(null)
    } else {
      const ok = await handleCreate(form)
      if (ok) setShowModal(false)
    }
  }

  return (
    <div className="space-y-6">
      <LicenseModuleBanner
        rule={2}
        sourceLabel="OWASP Top 10 / ASVS / SAMM (CC-BY-SA 4.0) + NIST SP 800-53 (US PD)"
        detail="OWASP-Inhalte zitiert mit Pflicht-Attribution 'OWASP Foundation, CC BY-SA 4.0'. NIST woertlich (R1)."
      />
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Security Backlog</h1>
          <p className="mt-1 text-gray-500">
            Verwalten Sie Sicherheitsbefunde und verfolgen Sie deren Behebung
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => { setEditItem(null); setShowModal(true) }}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Befund erfassen
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Offen</div>
          <div className="text-3xl font-bold text-gray-900">{stats.open}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-6">
          <div className="text-sm text-red-600">Kritisch</div>
          <div className="text-3xl font-bold text-red-600">{stats.critical}</div>
        </div>
        <div className="bg-white rounded-xl border border-orange-200 p-6">
          <div className="text-sm text-orange-600">Hoch</div>
          <div className="text-3xl font-bold text-orange-600">{stats.high}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Ueberfaellig</div>
          <div className="text-3xl font-bold text-yellow-600">{stats.overdue}</div>
        </div>
      </div>

      {/* Critical Alert */}
      {stats.critical > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-4">
          <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
            <svg className="w-5 h-5 text-red-600" 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>
          <div>
            <h4 className="font-medium text-red-800">{stats.critical} kritische Schwachstelle(n) erfordern sofortige Aufmerksamkeit</h4>
            <p className="text-sm text-red-600">Diese Befunde haben ein CVSS von 9.0 oder hoeher und sollten priorisiert werden.</p>
          </div>
        </div>
      )}

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'open', 'in-progress', 'critical', 'high', 'vulnerability', 'misconfiguration'].map(f => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-3 py-1 text-sm rounded-full transition-colors ${
              filter === f ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {f === 'all' ? 'Alle' : f === 'open' ? 'Offen' : f === 'in-progress' ? 'In Bearbeitung' :
             f === 'critical' ? 'Kritisch' : f === 'high' ? 'Hoch' :
             f === 'vulnerability' ? 'Schwachstellen' : 'Fehlkonfigurationen'}
          </button>
        ))}
      </div>

      {/* Items List */}
      {loading ? (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center text-gray-400">
          Lade Sicherheitsbefunde...
        </div>
      ) : (
        <div className="space-y-4">
          {filteredItems
            .sort((a, b) => {
              const sOrder = { critical: 0, high: 1, medium: 2, low: 3 }
              const stOrder = { open: 0, 'in-progress': 1, 'accepted-risk': 2, resolved: 3 }
              const sd = sOrder[a.severity] - sOrder[b.severity]
              if (sd !== 0) return sd
              return stOrder[a.status] - stOrder[b.status]
            })
            .map(item => (
              <SecurityItemCard
                key={item.id}
                item={item}
                onEdit={i => { setEditItem(i); setShowModal(true) }}
                onDelete={handleDelete}
                onStatusChange={handleStatusChange}
              />
            ))}

          {filteredItems.length === 0 && (
            <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
              <div className="w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center mb-4">
                <svg className="w-8 h-8 text-green-600" 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>
              </div>
              <h3 className="text-lg font-semibold text-gray-900">Keine Befunde gefunden</h3>
              <p className="mt-2 text-gray-500">Passen Sie den Filter an oder erfassen Sie einen neuen Befund.</p>
            </div>
          )}
        </div>
      )}

      {/* Create/Edit Modal */}
      {showModal && (
        <ItemModal
          item={editItem ? {
            title: editItem.title,
            description: editItem.description || '',
            type: editItem.type,
            severity: editItem.severity,
            source: editItem.source || '',
            cve: editItem.cve || '',
            cvss: editItem.cvss !== null ? String(editItem.cvss) : '',
            affected_asset: editItem.affected_asset || '',
            assigned_to: editItem.assigned_to || '',
            remediation: editItem.remediation || '',
          } : EMPTY_NEW_ITEM}
          onClose={() => { setShowModal(false); setEditItem(null) }}
          onSave={onSave}
        />
      )}
    </div>
  )
}
