'use client'

import React, { useState } from 'react'
import {
  DSFA,
  DSFARisk,
  DSFA_RISK_LEVEL_LABELS,
  DSFA_AFFECTED_RIGHTS,
  calculateRiskLevel,
} from '@/lib/sdk/dsfa/types'
import { RiskMatrix } from '@/components/sdk/dsfa'
import { RAGSearchPanel } from './RAGSearchPanel'
import { AddRiskModal } from './AddRiskModal'

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

export function Section3Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [selectedRisk, setSelectedRisk] = useState<DSFARisk | null>(null)
  const [showAddRiskModal, setShowAddRiskModal] = useState(false)
  const [newRiskLikelihood, setNewRiskLikelihood] = useState<'low' | 'medium' | 'high'>('medium')
  const [newRiskImpact, setNewRiskImpact] = useState<'low' | 'medium' | 'high'>('medium')
  const [affectedRights, setAffectedRights] = useState<string[]>(dsfa.affected_rights || [])

  const handleAddRisk = (likelihood: 'low' | 'medium' | 'high', impact: 'low' | 'medium' | 'high') => {
    setNewRiskLikelihood(likelihood)
    setNewRiskImpact(impact)
    setShowAddRiskModal(true)
  }

  const toggleAffectedRight = (rightId: string) => {
    setAffectedRights(prev =>
      prev.includes(rightId)
        ? prev.filter(r => r !== rightId)
        : [...prev, rightId]
    )
  }

  const handleSaveSection = () => {
    onUpdate({
      affected_rights: affectedRights,
      overall_risk_level: dsfa.overall_risk_level,
    })
  }

  const levelColors = {
    low: 'bg-green-100 text-green-700 border-green-200',
    medium: 'bg-yellow-100 text-yellow-700 border-yellow-200',
    high: 'bg-orange-100 text-orange-700 border-orange-200',
    very_high: 'bg-red-100 text-red-700 border-red-200',
  }

  return (
    <div className="space-y-6">
      {/* Risk Matrix */}
      <div className="bg-gray-50 rounded-xl p-6">
        <RiskMatrix
          risks={dsfa.risks || []}
          onRiskSelect={(risk) => setSelectedRisk(risk as DSFARisk)}
          onAddRisk={handleAddRisk}
          selectedRiskId={selectedRisk?.id}
          readOnly={dsfa.status !== 'draft' && dsfa.status !== 'needs_update'}
        />
      </div>

      {/* Triggered Rules from UCCA */}
      {dsfa.triggered_rule_codes && dsfa.triggered_rule_codes.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4">
          <h4 className="text-sm font-medium text-red-800 mb-2">
            DSFA-ausloesende Regeln (aus UCCA)
          </h4>
          <div className="flex flex-wrap gap-2">
            {dsfa.triggered_rule_codes.map(code => (
              <span key={code} className="px-2 py-1 bg-red-100 text-red-700 rounded text-xs">
                {code}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Risk List */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">Identifizierte Risiken ({(dsfa.risks || []).length})</h4>
        {(dsfa.risks || []).length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <svg className="w-12 h-12 mx-auto text-gray-300 mb-3" 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>
            <p>Noch keine Risiken erfasst</p>
            <p className="text-sm mt-1">Klicken Sie in der Matrix auf eine Zelle, um ein Risiko hinzuzufuegen.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {(dsfa.risks || []).map(risk => {
              const { level } = calculateRiskLevel(risk.likelihood, risk.impact)
              return (
                <div
                  key={risk.id}
                  className={`p-4 rounded-xl border cursor-pointer transition-all ${
                    selectedRisk?.id === risk.id ? 'ring-2 ring-purple-500' : ''
                  } ${levelColors[level]}`}
                  onClick={() => setSelectedRisk(risk)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="font-medium">{risk.description}</div>
                      <div className="text-sm mt-1 opacity-75">
                        Kategorie: {risk.category === 'confidentiality' ? 'Vertraulichkeit' :
                                    risk.category === 'integrity' ? 'Integritaet' :
                                    risk.category === 'availability' ? 'Verfuegbarkeit' :
                                    'Rechte & Freiheiten'}
                      </div>
                      <div className="text-sm opacity-75">
                        Eintrittswahrscheinlichkeit: {risk.likelihood === 'low' ? 'Niedrig' : risk.likelihood === 'medium' ? 'Mittel' : 'Hoch'} |
                        Auswirkung: {risk.impact === 'low' ? 'Niedrig' : risk.impact === 'medium' ? 'Mittel' : 'Hoch'}
                      </div>
                    </div>
                    <span className={`px-2 py-1 rounded text-xs font-medium ${levelColors[level]}`}>
                      {DSFA_RISK_LEVEL_LABELS[level]}
                    </span>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>

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

      {/* Affected Rights */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">Betroffene Rechte & Freiheiten</h4>
        <div className="grid grid-cols-2 gap-2">
          {DSFA_AFFECTED_RIGHTS.map(right => (
            <label
              key={right.id}
              className={`flex items-center gap-2 p-3 rounded-lg border cursor-pointer transition-colors ${
                affectedRights.includes(right.id)
                  ? 'bg-purple-50 border-purple-300'
                  : 'bg-white border-gray-200 hover:bg-gray-50'
              }`}
            >
              <input
                type="checkbox"
                checked={affectedRights.includes(right.id)}
                onChange={() => toggleAffectedRight(right.id)}
                className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
              />
              <span className="text-sm">{right.label}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleSaveSection}
          disabled={isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
        >
          {isSubmitting ? 'Speichern...' : 'Abschnitt speichern'}
        </button>
      </div>

      {/* Add Risk Modal */}
      {showAddRiskModal && (
        <AddRiskModal
          likelihood={newRiskLikelihood}
          impact={newRiskImpact}
          onClose={() => setShowAddRiskModal(false)}
          onAdd={async (riskData) => {
            // This would call the API
            setShowAddRiskModal(false)
          }}
        />
      )}
    </div>
  )
}
