'use client'

import React, { useState, useEffect } from 'react'
import { useSDK, Risk, RiskLikelihood, RiskImpact, RiskSeverity, RiskStatus, RiskMitigation, calculateRiskScore, getRiskSeverityFromScore } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'

// =============================================================================
// RISK MATRIX
// =============================================================================

function RiskMatrix({ risks, onCellClick }: { risks: Risk[]; onCellClick: (l: number, i: number) => void }) {
  const matrix: Record<string, Risk[]> = {}

  risks.forEach(risk => {
    const key = `${risk.likelihood}-${risk.impact}`
    if (!matrix[key]) matrix[key] = []
    matrix[key].push(risk)
  })

  const getCellColor = (likelihood: number, impact: number): string => {
    const score = likelihood * impact
    if (score >= 20) return 'bg-red-500'
    if (score >= 15) return 'bg-red-400'
    if (score >= 12) return 'bg-orange-400'
    if (score >= 8) return 'bg-yellow-400'
    if (score >= 4) return 'bg-yellow-300'
    return 'bg-green-400'
  }

  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">5x5 Risikomatrix</h3>
      <div className="flex">
        {/* Y-Axis Label */}
        <div className="flex flex-col justify-center pr-2">
          <div className="transform -rotate-90 whitespace-nowrap text-sm text-gray-500 font-medium">
            Wahrscheinlichkeit
          </div>
        </div>

        <div className="flex-1">
          {/* Matrix Grid */}
          <div className="grid grid-cols-5 gap-1">
            {[5, 4, 3, 2, 1].map(likelihood => (
              <React.Fragment key={likelihood}>
                {[1, 2, 3, 4, 5].map(impact => {
                  const key = `${likelihood}-${impact}`
                  const cellRisks = matrix[key] || []
                  return (
                    <button
                      key={key}
                      onClick={() => onCellClick(likelihood, impact)}
                      className={`aspect-square rounded-lg ${getCellColor(
                        likelihood,
                        impact
                      )} hover:opacity-80 transition-opacity relative`}
                    >
                      {cellRisks.length > 0 && (
                        <span className="absolute inset-0 flex items-center justify-center text-white font-bold text-lg">
                          {cellRisks.length}
                        </span>
                      )}
                    </button>
                  )
                })}
              </React.Fragment>
            ))}
          </div>

          {/* X-Axis Label */}
          <div className="mt-2 text-center text-sm text-gray-500 font-medium">Auswirkung</div>
        </div>
      </div>

      {/* Legend */}
      <div className="mt-6 flex items-center justify-center gap-4 text-sm">
        <div className="flex items-center gap-2">
          <div className="w-4 h-4 rounded bg-green-400" />
          <span>Niedrig</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-4 h-4 rounded bg-yellow-400" />
          <span>Mittel</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-4 h-4 rounded bg-orange-400" />
          <span>Hoch</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-4 h-4 rounded bg-red-500" />
          <span>Kritisch</span>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// RISK FORM
// =============================================================================

interface RiskFormData {
  title: string
  description: string
  category: string
  likelihood: RiskLikelihood
  impact: RiskImpact
}

function RiskForm({
  onSubmit,
  onCancel,
  initialData,
}: {
  onSubmit: (data: RiskFormData) => void
  onCancel: () => void
  initialData?: Partial<RiskFormData>
}) {
  const [formData, setFormData] = useState<RiskFormData>({
    title: initialData?.title || '',
    description: initialData?.description || '',
    category: initialData?.category || 'technical',
    likelihood: initialData?.likelihood || 3,
    impact: initialData?.impact || 3,
  })

  const score = calculateRiskScore(formData.likelihood, formData.impact)
  const severity = getRiskSeverityFromScore(score)

  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">
        {initialData ? 'Risiko bearbeiten' : 'Neues Risiko'}
      </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={formData.title}
            onChange={e => setFormData({ ...formData, title: e.target.value })}
            placeholder="z.B. Datenverlust durch Systemausfall"
            className="w-full px-4 py-2 border border-gray-300 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={formData.description}
            onChange={e => setFormData({ ...formData, description: e.target.value })}
            placeholder="Beschreiben Sie das Risiko..."
            rows={3}
            className="w-full px-4 py-2 border border-gray-300 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">Kategorie</label>
          <select
            value={formData.category}
            onChange={e => setFormData({ ...formData, category: e.target.value })}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          >
            <option value="technical">Technisch</option>
            <option value="organizational">Organisatorisch</option>
            <option value="legal">Rechtlich</option>
            <option value="operational">Operativ</option>
            <option value="strategic">Strategisch</option>
          </select>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Wahrscheinlichkeit (1-5)
            </label>
            <input
              type="range"
              min={1}
              max={5}
              value={formData.likelihood}
              onChange={e => setFormData({ ...formData, likelihood: Number(e.target.value) as RiskLikelihood })}
              className="w-full"
            />
            <div className="flex justify-between text-xs text-gray-500 mt-1">
              <span>Sehr unwahrscheinlich</span>
              <span className="font-bold">{formData.likelihood}</span>
              <span>Sehr wahrscheinlich</span>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Auswirkung (1-5)</label>
            <input
              type="range"
              min={1}
              max={5}
              value={formData.impact}
              onChange={e => setFormData({ ...formData, impact: Number(e.target.value) as RiskImpact })}
              className="w-full"
            />
            <div className="flex justify-between text-xs text-gray-500 mt-1">
              <span>Gering</span>
              <span className="font-bold">{formData.impact}</span>
              <span>Katastrophal</span>
            </div>
          </div>
        </div>

        {/* Risk Score Preview */}
        <div
          className={`p-4 rounded-lg ${
            severity === 'CRITICAL'
              ? 'bg-red-50 border border-red-200'
              : severity === 'HIGH'
              ? 'bg-orange-50 border border-orange-200'
              : severity === 'MEDIUM'
              ? 'bg-yellow-50 border border-yellow-200'
              : 'bg-green-50 border border-green-200'
          }`}
        >
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">Berechneter Risikoscore:</span>
            <span
              className={`px-3 py-1 rounded-full text-sm font-bold ${
                severity === 'CRITICAL'
                  ? 'bg-red-100 text-red-700'
                  : severity === 'HIGH'
                  ? 'bg-orange-100 text-orange-700'
                  : severity === 'MEDIUM'
                  ? 'bg-yellow-100 text-yellow-700'
                  : 'bg-green-100 text-green-700'
              }`}
            >
              {score} ({severity})
            </span>
          </div>
        </div>
      </div>

      <div className="mt-6 flex items-center justify-end gap-3">
        <button
          onClick={onCancel}
          className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
        >
          Abbrechen
        </button>
        <button
          onClick={() => onSubmit(formData)}
          disabled={!formData.title}
          className={`px-6 py-2 rounded-lg font-medium transition-colors ${
            formData.title
              ? 'bg-purple-600 text-white hover:bg-purple-700'
              : 'bg-gray-200 text-gray-400 cursor-not-allowed'
          }`}
        >
          Speichern
        </button>
      </div>
    </div>
  )
}

// =============================================================================
// RISK CARD
// =============================================================================

function RiskCard({
  risk,
  onEdit,
  onDelete,
}: {
  risk: Risk
  onEdit: () => void
  onDelete: () => void
}) {
  const severityColors = {
    CRITICAL: 'border-red-200 bg-red-50',
    HIGH: 'border-orange-200 bg-orange-50',
    MEDIUM: 'border-yellow-200 bg-yellow-50',
    LOW: 'border-green-200 bg-green-50',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${severityColors[risk.severity]}`}>
      <div className="flex items-start justify-between">
        <div>
          <div className="flex items-center gap-2">
            <h4 className="font-semibold text-gray-900">{risk.title}</h4>
            <span
              className={`px-2 py-0.5 text-xs rounded-full ${
                risk.severity === 'CRITICAL'
                  ? 'bg-red-100 text-red-700'
                  : risk.severity === 'HIGH'
                  ? 'bg-orange-100 text-orange-700'
                  : risk.severity === 'MEDIUM'
                  ? 'bg-yellow-100 text-yellow-700'
                  : 'bg-green-100 text-green-700'
              }`}
            >
              {risk.severity}
            </span>
          </div>
          <p className="text-sm text-gray-500 mt-1">{risk.description}</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={onEdit}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
              />
            </svg>
          </button>
          <button
            onClick={onDelete}
            className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
              />
            </svg>
          </button>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-3 gap-4 text-sm">
        <div>
          <span className="text-gray-500">Wahrscheinlichkeit:</span>
          <span className="ml-2 font-medium">{risk.likelihood}/5</span>
        </div>
        <div>
          <span className="text-gray-500">Auswirkung:</span>
          <span className="ml-2 font-medium">{risk.impact}/5</span>
        </div>
        <div>
          <span className="text-gray-500">Score:</span>
          <span className="ml-2 font-medium">{risk.inherentRiskScore}</span>
        </div>
      </div>

      {risk.mitigation.length > 0 && (
        <div className="mt-4 pt-4 border-t border-gray-200">
          <span className="text-sm text-gray-500">Mitigationen: {risk.mitigation.length}</span>
        </div>
      )}
    </div>
  )
}

function LoadingSkeleton() {
  return (
    <div className="space-y-4">
      {[1, 2, 3].map(i => (
        <div key={i} className="bg-white rounded-xl border border-gray-200 p-6 animate-pulse">
          <div className="h-6 w-3/4 bg-gray-200 rounded mb-2" />
          <div className="h-4 w-full bg-gray-100 rounded mb-4" />
          <div className="grid grid-cols-3 gap-4">
            <div className="h-4 bg-gray-200 rounded" />
            <div className="h-4 bg-gray-200 rounded" />
            <div className="h-4 bg-gray-200 rounded" />
          </div>
        </div>
      ))}
    </div>
  )
}

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

export default function RisksPage() {
  const { state, dispatch, addRisk } = useSDK()
  const [showForm, setShowForm] = useState(false)
  const [editingRisk, setEditingRisk] = useState<Risk | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Fetch risks from backend on mount
  useEffect(() => {
    const fetchRisks = async () => {
      try {
        setLoading(true)
        const res = await fetch('/api/sdk/v1/compliance/risks')
        if (res.ok) {
          const data = await res.json()
          const backendRisks = data.risks || data
          if (Array.isArray(backendRisks) && backendRisks.length > 0) {
            const mapped: Risk[] = backendRisks.map((r: Record<string, unknown>) => ({
              id: (r.risk_id || r.id || '') as string,
              title: (r.title || '') as string,
              description: (r.description || '') as string,
              category: (r.category || 'technical') as string,
              likelihood: (r.likelihood || 3) as RiskLikelihood,
              impact: (r.impact || 3) as RiskImpact,
              severity: ((r.inherent_risk || r.severity || 'MEDIUM') as string).toUpperCase() as RiskSeverity,
              inherentRiskScore: (r.likelihood as number || 3) * (r.impact as number || 3),
              residualRiskScore: (r.residual_likelihood as number || r.likelihood as number || 3) * (r.residual_impact as number || r.impact as number || 3),
              status: (r.status || 'IDENTIFIED') as RiskStatus,
              mitigation: (Array.isArray(r.mitigating_controls) ? (r.mitigating_controls as RiskMitigation[]) : []) as RiskMitigation[],
              owner: (r.owner || null) as string | null,
              relatedControls: [] as string[],
              relatedRequirements: [] as string[],
            }))
            dispatch({ type: 'SET_STATE', payload: { risks: mapped } })
            setError(null)
          }
        }
      } catch {
        // Backend unavailable — use SDK state as-is
      } finally {
        setLoading(false)
      }
    }

    fetchRisks()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  const handleSubmit = async (data: { title: string; description: string; category: string; likelihood: RiskLikelihood; impact: RiskImpact }) => {
    const score = calculateRiskScore(data.likelihood, data.impact)
    const severity = getRiskSeverityFromScore(score)

    if (editingRisk) {
      dispatch({
        type: 'UPDATE_RISK',
        payload: {
          id: editingRisk.id,
          data: {
            ...data,
            severity,
            inherentRiskScore: score,
            residualRiskScore: score,
          },
        },
      })

      // Persist to backend
      try {
        await fetch(`/api/sdk/v1/compliance/risks/${editingRisk.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            title: data.title,
            description: data.description,
            category: data.category,
            likelihood: data.likelihood,
            impact: data.impact,
          }),
        })
      } catch {
        // Silently fail
      }
    } else {
      const riskId = `risk-${Date.now()}`
      const newRisk: Risk = {
        id: riskId,
        ...data,
        severity,
        inherentRiskScore: score,
        residualRiskScore: score,
        status: 'IDENTIFIED',
        mitigation: [],
        owner: null,
        relatedControls: [],
        relatedRequirements: [],
      }
      addRisk(newRisk)

      // Persist to backend
      try {
        await fetch('/api/sdk/v1/compliance/risks', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            risk_id: riskId,
            title: data.title,
            description: data.description,
            category: data.category,
            likelihood: data.likelihood,
            impact: data.impact,
          }),
        })
      } catch {
        // Silently fail
      }
    }

    setShowForm(false)
    setEditingRisk(null)
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Moechten Sie dieses Risiko wirklich loeschen?')) return

    dispatch({ type: 'DELETE_RISK', payload: id })

    try {
      await fetch(`/api/sdk/v1/compliance/risks/${id}`, {
        method: 'DELETE',
      })
    } catch {
      // Silently fail
    }
  }

  const handleEdit = (risk: Risk) => {
    setEditingRisk(risk)
    setShowForm(true)
  }

  // Stats
  const totalRisks = state.risks.length
  const criticalRisks = state.risks.filter(r => r.severity === 'CRITICAL').length
  const highRisks = state.risks.filter(r => r.severity === 'HIGH').length
  const mitigatedRisks = state.risks.filter(r => r.mitigation.length > 0).length

  const stepInfo = STEP_EXPLANATIONS['risks']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="risks"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        {!showForm && (
          <button
            onClick={() => setShowForm(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>
            Risiko hinzufuegen
          </button>
        )}
      </StepHeader>

      {/* Error Banner */}
      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="text-red-500 hover:text-red-700">&times;</button>
        </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">Gesamt</div>
          <div className="text-3xl font-bold text-gray-900">{totalRisks}</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">{criticalRisks}</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">{highRisks}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Mit Mitigation</div>
          <div className="text-3xl font-bold text-green-600">{mitigatedRisks}</div>
        </div>
      </div>

      {/* Form */}
      {showForm && (
        <RiskForm
          onSubmit={handleSubmit}
          onCancel={() => {
            setShowForm(false)
            setEditingRisk(null)
          }}
          initialData={editingRisk || undefined}
        />
      )}

      {/* Loading */}
      {loading && <LoadingSkeleton />}

      {/* Matrix */}
      {!loading && <RiskMatrix risks={state.risks} onCellClick={() => {}} />}

      {/* Risk List */}
      {!loading && state.risks.length > 0 && (
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Alle Risiken</h3>
          <div className="space-y-4">
            {state.risks
              .sort((a, b) => b.inherentRiskScore - a.inherentRiskScore)
              .map(risk => (
                <RiskCard
                  key={risk.id}
                  risk={risk}
                  onEdit={() => handleEdit(risk)}
                  onDelete={() => handleDelete(risk.id)}
                />
              ))}
          </div>
        </div>
      )}

      {/* Empty State */}
      {!loading && state.risks.length === 0 && !showForm && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-orange-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-orange-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>
          <h3 className="text-lg font-semibold text-gray-900">Keine Risiken erfasst</h3>
          <p className="mt-2 text-gray-500 max-w-md mx-auto">
            Beginnen Sie mit der Erfassung von Risiken fuer Ihre KI-Anwendungen.
          </p>
          <button
            onClick={() => setShowForm(true)}
            className="mt-6 px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            Erstes Risiko erfassen
          </button>
        </div>
      )}
    </div>
  )
}
