'use client'

import React, { useState } from 'react'
import { DSFA, DSFAMitigation } from '@/lib/sdk/dsfa/types'
import { RAGSearchPanel } from './RAGSearchPanel'
import { AddMitigationModal } from './AddMitigationModal'

interface SectionProps {
  dsfa: DSFA
  onUpdate: (data: Record<string, unknown>) => Promise<void>
  isSubmitting: boolean
}

export function Section4Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [showAddMitigation, setShowAddMitigation] = useState(false)

  const mitigationsByType = {
    technical: (dsfa.mitigations || []).filter(m => m.type === 'technical'),
    organizational: (dsfa.mitigations || []).filter(m => m.type === 'organizational'),
    legal: (dsfa.mitigations || []).filter(m => m.type === 'legal'),
  }

  const getStatusBadge = (status: string) => {
    const styles = {
      planned: 'bg-gray-100 text-gray-600',
      in_progress: 'bg-yellow-100 text-yellow-700',
      implemented: 'bg-blue-100 text-blue-700',
      verified: 'bg-green-100 text-green-700',
    }
    const labels = {
      planned: 'Geplant',
      in_progress: 'In Umsetzung',
      implemented: 'Umgesetzt',
      verified: 'Verifiziert',
    }
    return (
      <span className={`px-2 py-1 rounded text-xs font-medium ${styles[status as keyof typeof styles] || styles.planned}`}>
        {labels[status as keyof typeof labels] || status}
      </span>
    )
  }

  const renderMitigationSection = (
    title: string,
    icon: React.ReactNode,
    mitigations: DSFAMitigation[],
    bgColor: string
  ) => (
    <div>
      <div className="flex items-center gap-2 mb-3">
        {icon}
        <h4 className="text-sm font-medium text-gray-700">{title} ({mitigations.length})</h4>
      </div>
      {mitigations.length === 0 ? (
        <div className={`p-4 rounded-lg ${bgColor} text-center text-sm text-gray-500`}>
          Keine Massnahmen definiert
        </div>
      ) : (
        <div className="space-y-2">
          {mitigations.map(m => (
            <div key={m.id} className={`p-4 rounded-lg ${bgColor} border border-gray-200`}>
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="font-medium text-gray-900">{m.description}</div>
                  <div className="text-sm text-gray-500 mt-1">
                    Verantwortlich: {m.responsible_party || '-'}
                    {m.tom_reference && ` | TOM: ${m.tom_reference}`}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {getStatusBadge(m.status)}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )

  return (
    <div className="space-y-6">
      {/* Add Mitigation Button */}
      <div className="flex justify-end">
        <button
          onClick={() => setShowAddMitigation(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 4v16m8-8H4" />
          </svg>
          Massnahme hinzufuegen
        </button>
      </div>

      {/* Technical Measures */}
      {renderMitigationSection(
        'Technische Massnahmen',
        <svg className="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
        </svg>,
        mitigationsByType.technical,
        'bg-blue-50'
      )}

      {/* Organizational Measures */}
      {renderMitigationSection(
        'Organisatorische Massnahmen',
        <svg className="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
        </svg>,
        mitigationsByType.organizational,
        'bg-green-50'
      )}

      {/* Legal Measures */}
      {renderMitigationSection(
        'Rechtliche Massnahmen',
        <svg className="w-5 h-5 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" />
        </svg>,
        mitigationsByType.legal,
        'bg-purple-50'
      )}

      {/* RAG Search for Mitigations */}
      <RAGSearchPanel
        context={`Massnahmen Datenschutz-Folgenabschaetzung ${dsfa.processing_description || ''} ${dsfa.processing_purpose || ''}`}
        categories={['mitigation', 'risk_assessment']}
      />

      {/* TOM References */}
      {dsfa.tom_references && dsfa.tom_references.length > 0 && (
        <div className="bg-gray-50 rounded-xl p-4">
          <h4 className="text-sm font-medium text-gray-700 mb-2">Verknuepfte TOM-Eintraege</h4>
          <div className="flex flex-wrap gap-2">
            {dsfa.tom_references.map((ref, idx) => (
              <span key={idx} className="px-3 py-1 bg-white border border-gray-200 rounded-full text-sm text-gray-600">
                {ref}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Add Mitigation Modal */}
      {showAddMitigation && (
        <AddMitigationModal
          risks={dsfa.risks || []}
          onClose={() => setShowAddMitigation(false)}
          onAdd={async (mitigationData) => {
            // This would call the API
            setShowAddMitigation(false)
          }}
        />
      )}
    </div>
  )
}
