'use client'

/**
 * Risk Matrix Page
 *
 * Features:
 * - Visual 5x5 risk matrix
 * - Risk list with CRUD
 * - Risk assessment / update
 */

import { useState, useEffect } from 'react'
import Link from 'next/link'
import AdminLayout from '@/components/admin/AdminLayout'

interface Risk {
  id: string
  risk_id: string
  title: string
  description: string
  category: string
  likelihood: number
  impact: number
  inherent_risk: string
  mitigating_controls: string[] | null
  residual_likelihood: number | null
  residual_impact: number | null
  residual_risk: string | null
  owner: string
  status: string
  treatment_plan: string
}

const RISK_COLORS: Record<string, string> = {
  low: 'bg-green-500',
  medium: 'bg-yellow-500',
  high: 'bg-orange-500',
  critical: 'bg-red-500',
}

const RISK_BG_COLORS: Record<string, string> = {
  low: 'bg-green-100 border-green-300',
  medium: 'bg-yellow-100 border-yellow-300',
  high: 'bg-orange-100 border-orange-300',
  critical: 'bg-red-100 border-red-300',
}

const STATUS_OPTIONS = ['open', 'mitigated', 'accepted', 'transferred']

const CATEGORY_OPTIONS = [
  { value: 'data_breach', label: 'Datenschutzverletzung' },
  { value: 'compliance_gap', label: 'Compliance-Luecke' },
  { value: 'vendor_risk', label: 'Lieferantenrisiko' },
  { value: 'operational', label: 'Betriebsrisiko' },
  { value: 'technical', label: 'Technisches Risiko' },
  { value: 'legal', label: 'Rechtliches Risiko' },
]

const calculateRiskLevel = (likelihood: number, impact: number): string => {
  const score = likelihood * impact
  if (score >= 20) return 'critical'
  if (score >= 12) return 'high'
  if (score >= 6) return 'medium'
  return 'low'
}

export default function RisksPage() {
  const [risks, setRisks] = useState<Risk[]>([])
  const [loading, setLoading] = useState(true)
  const [viewMode, setViewMode] = useState<'matrix' | 'list'>('matrix')
  const [selectedRisk, setSelectedRisk] = useState<Risk | null>(null)
  const [editModalOpen, setEditModalOpen] = useState(false)
  const [createModalOpen, setCreateModalOpen] = useState(false)

  const [formData, setFormData] = useState({
    risk_id: '',
    title: '',
    description: '',
    category: 'compliance_gap',
    likelihood: 3,
    impact: 3,
    owner: '',
    treatment_plan: '',
    status: 'open',
    mitigating_controls: [] as string[],
    residual_likelihood: null as number | null,
    residual_impact: null as number | null,
  })

  const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000'

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

  const loadRisks = async () => {
    setLoading(true)
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/risks`)
      if (res.ok) {
        const data = await res.json()
        setRisks(data.risks || [])
      }
    } catch (error) {
      console.error('Failed to load risks:', error)
    } finally {
      setLoading(false)
    }
  }

  const openCreateModal = () => {
    setFormData({
      risk_id: `RISK-${String(risks.length + 1).padStart(3, '0')}`,
      title: '',
      description: '',
      category: 'compliance_gap',
      likelihood: 3,
      impact: 3,
      owner: '',
      treatment_plan: '',
      status: 'open',
      mitigating_controls: [],
      residual_likelihood: null,
      residual_impact: null,
    })
    setCreateModalOpen(true)
  }

  const openEditModal = (risk: Risk) => {
    setSelectedRisk(risk)
    setFormData({
      risk_id: risk.risk_id,
      title: risk.title,
      description: risk.description || '',
      category: risk.category,
      likelihood: risk.likelihood,
      impact: risk.impact,
      owner: risk.owner || '',
      treatment_plan: risk.treatment_plan || '',
      status: risk.status,
      mitigating_controls: risk.mitigating_controls || [],
      residual_likelihood: risk.residual_likelihood,
      residual_impact: risk.residual_impact,
    })
    setEditModalOpen(true)
  }

  const handleCreate = async () => {
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/risks`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          risk_id: formData.risk_id,
          title: formData.title,
          description: formData.description,
          category: formData.category,
          likelihood: formData.likelihood,
          impact: formData.impact,
          owner: formData.owner,
          treatment_plan: formData.treatment_plan,
          mitigating_controls: formData.mitigating_controls,
        }),
      })

      if (res.ok) {
        setCreateModalOpen(false)
        loadRisks()
      } else {
        const error = await res.text()
        alert(`Fehler: ${error}`)
      }
    } catch (error) {
      console.error('Create failed:', error)
      alert('Fehler beim Erstellen')
    }
  }

  const handleUpdate = async () => {
    if (!selectedRisk) return

    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/risks/${selectedRisk.risk_id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: formData.title,
          description: formData.description,
          category: formData.category,
          likelihood: formData.likelihood,
          impact: formData.impact,
          owner: formData.owner,
          treatment_plan: formData.treatment_plan,
          status: formData.status,
          mitigating_controls: formData.mitigating_controls,
          residual_likelihood: formData.residual_likelihood,
          residual_impact: formData.residual_impact,
        }),
      })

      if (res.ok) {
        setEditModalOpen(false)
        loadRisks()
      } else {
        const error = await res.text()
        alert(`Fehler: ${error}`)
      }
    } catch (error) {
      console.error('Update failed:', error)
      alert('Fehler beim Aktualisieren')
    }
  }

  // Build matrix data structure
  const buildMatrix = () => {
    const matrix: Record<number, Record<number, Risk[]>> = {}
    for (let l = 1; l <= 5; l++) {
      matrix[l] = {}
      for (let i = 1; i <= 5; i++) {
        matrix[l][i] = []
      }
    }
    risks.forEach((risk) => {
      if (matrix[risk.likelihood] && matrix[risk.likelihood][risk.impact]) {
        matrix[risk.likelihood][risk.impact].push(risk)
      }
    })
    return matrix
  }

  const renderMatrix = () => {
    const matrix = buildMatrix()

    return (
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-lg font-semibold text-slate-900 mb-4">Risk Matrix (Likelihood x Impact)</h3>

        <div className="overflow-x-auto">
          <div className="inline-block">
            {/* Column headers (Impact) */}
            <div className="flex ml-16">
              {[1, 2, 3, 4, 5].map((i) => (
                <div key={i} className="w-24 text-center text-sm font-medium text-slate-500 pb-2">
                  Impact {i}
                </div>
              ))}
            </div>

            {/* Matrix rows */}
            {[5, 4, 3, 2, 1].map((likelihood) => (
              <div key={likelihood} className="flex items-center">
                <div className="w-16 text-sm font-medium text-slate-500 text-right pr-2">
                  L{likelihood}
                </div>
                {[1, 2, 3, 4, 5].map((impact) => {
                  const level = calculateRiskLevel(likelihood, impact)
                  const cellRisks = matrix[likelihood][impact]

                  return (
                    <div
                      key={impact}
                      className={`w-24 h-20 border m-0.5 rounded flex flex-col items-center justify-center ${RISK_BG_COLORS[level]}`}
                    >
                      {cellRisks.length > 0 && (
                        <div className="flex flex-wrap gap-1 justify-center">
                          {cellRisks.map((r) => (
                            <button
                              key={r.id}
                              onClick={() => openEditModal(r)}
                              className={`px-2 py-0.5 text-xs font-medium rounded text-white ${RISK_COLORS[r.inherent_risk] || 'bg-slate-500'} hover:opacity-80`}
                              title={r.title}
                            >
                              {r.risk_id}
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            ))}
          </div>
        </div>

        {/* Legend */}
        <div className="flex gap-4 mt-6 pt-4 border-t">
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-green-500 rounded" />
            <span className="text-sm text-slate-600">Low (1-5)</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-yellow-500 rounded" />
            <span className="text-sm text-slate-600">Medium (6-11)</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-orange-500 rounded" />
            <span className="text-sm text-slate-600">High (12-19)</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-red-500 rounded" />
            <span className="text-sm text-slate-600">Critical (20-25)</span>
          </div>
        </div>
      </div>
    )
  }

  const renderList = () => (
    <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
      <table className="w-full">
        <thead className="bg-slate-50">
          <tr>
            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">ID</th>
            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Titel</th>
            <th className="px-4 py-3 text-center text-xs font-medium text-slate-500 uppercase">Kategorie</th>
            <th className="px-4 py-3 text-center text-xs font-medium text-slate-500 uppercase">L x I</th>
            <th className="px-4 py-3 text-center text-xs font-medium text-slate-500 uppercase">Risiko</th>
            <th className="px-4 py-3 text-center text-xs font-medium text-slate-500 uppercase">Status</th>
            <th className="px-4 py-3 text-right text-xs font-medium text-slate-500 uppercase">Aktionen</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-200">
          {risks.map((risk) => (
            <tr key={risk.id} className="hover:bg-slate-50">
              <td className="px-4 py-3">
                <span className="font-mono font-medium text-primary-600">{risk.risk_id}</span>
              </td>
              <td className="px-4 py-3">
                <div>
                  <p className="font-medium text-slate-900">{risk.title}</p>
                  {risk.description && (
                    <p className="text-sm text-slate-500 truncate max-w-md">{risk.description}</p>
                  )}
                </div>
              </td>
              <td className="px-4 py-3 text-center">
                <span className="text-sm text-slate-600">
                  {CATEGORY_OPTIONS.find((c) => c.value === risk.category)?.label || risk.category}
                </span>
              </td>
              <td className="px-4 py-3 text-center">
                <span className="font-mono">{risk.likelihood} x {risk.impact}</span>
              </td>
              <td className="px-4 py-3 text-center">
                <span className={`px-2 py-1 text-xs font-medium rounded-full text-white ${RISK_COLORS[risk.inherent_risk] || 'bg-slate-500'}`}>
                  {risk.inherent_risk}
                </span>
              </td>
              <td className="px-4 py-3 text-center">
                <span className={`px-2 py-1 text-xs rounded-full ${
                  risk.status === 'mitigated' ? 'bg-green-100 text-green-700' :
                  risk.status === 'accepted' ? 'bg-blue-100 text-blue-700' :
                  'bg-slate-100 text-slate-700'
                }`}>
                  {risk.status}
                </span>
              </td>
              <td className="px-4 py-3 text-right">
                <button
                  onClick={() => openEditModal(risk)}
                  className="text-sm text-primary-600 hover:text-primary-700 font-medium"
                >
                  Bearbeiten
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )

  const renderForm = (isCreate: boolean) => (
    <div className="space-y-4">
      {isCreate && (
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Risk ID</label>
          <input
            type="text"
            value={formData.risk_id}
            onChange={(e) => setFormData({ ...formData, risk_id: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
          />
        </div>
      )}

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Titel *</label>
        <input
          type="text"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Beschreibung</label>
        <textarea
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          rows={2}
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Kategorie</label>
          <select
            value={formData.category}
            onChange={(e) => setFormData({ ...formData, category: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
          >
            {CATEGORY_OPTIONS.map((c) => (
              <option key={c.value} value={c.value}>{c.label}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Status</label>
          <select
            value={formData.status}
            onChange={(e) => setFormData({ ...formData, status: e.target.value })}
            className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
          >
            {STATUS_OPTIONS.map((s) => (
              <option key={s} value={s}>{s}</option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Likelihood (1-5)</label>
          <input
            type="range"
            min="1"
            max="5"
            value={formData.likelihood}
            onChange={(e) => setFormData({ ...formData, likelihood: parseInt(e.target.value) })}
            className="w-full"
          />
          <div className="flex justify-between text-xs text-slate-500">
            <span>1</span>
            <span className="font-medium">{formData.likelihood}</span>
            <span>5</span>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Impact (1-5)</label>
          <input
            type="range"
            min="1"
            max="5"
            value={formData.impact}
            onChange={(e) => setFormData({ ...formData, impact: parseInt(e.target.value) })}
            className="w-full"
          />
          <div className="flex justify-between text-xs text-slate-500">
            <span>1</span>
            <span className="font-medium">{formData.impact}</span>
            <span>5</span>
          </div>
        </div>
      </div>

      <div className="p-3 bg-slate-50 rounded-lg">
        <p className="text-sm text-slate-600">
          Berechnetes Risiko:{' '}
          <span className={`font-medium px-2 py-0.5 rounded text-white ${RISK_COLORS[calculateRiskLevel(formData.likelihood, formData.impact)]}`}>
            {calculateRiskLevel(formData.likelihood, formData.impact).toUpperCase()} ({formData.likelihood * formData.impact})
          </span>
        </p>
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Verantwortlich</label>
        <input
          type="text"
          value={formData.owner}
          onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Behandlungsplan</label>
        <textarea
          value={formData.treatment_plan}
          onChange={(e) => setFormData({ ...formData, treatment_plan: e.target.value })}
          rows={2}
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
        />
      </div>
    </div>
  )

  return (
    <AdminLayout title="Risk Matrix" description="Risikobewertung & Management">
      {/* Header */}
      <div className="flex flex-wrap items-center gap-4 mb-6">
        <Link
          href="/admin/compliance"
          className="text-sm text-slate-500 hover:text-slate-700 flex items-center gap-1"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          Zurueck
        </Link>

        <div className="flex-1" />

        {/* View Toggle */}
        <div className="flex bg-slate-100 rounded-lg p-1">
          <button
            onClick={() => setViewMode('matrix')}
            className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
              viewMode === 'matrix' ? 'bg-white shadow text-slate-900' : 'text-slate-600'
            }`}
          >
            Matrix
          </button>
          <button
            onClick={() => setViewMode('list')}
            className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
              viewMode === 'list' ? 'bg-white shadow text-slate-900' : 'text-slate-600'
            }`}
          >
            Liste
          </button>
        </div>

        <button
          onClick={openCreateModal}
          className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
        >
          Risiko hinzufuegen
        </button>
      </div>

      {/* Content */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
        </div>
      ) : risks.length === 0 ? (
        <div className="bg-white rounded-xl shadow-sm border p-12 text-center">
          <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" 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 className="text-slate-500 mb-4">Keine Risiken erfasst</p>
          <button
            onClick={openCreateModal}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
          >
            Erstes Risiko hinzufuegen
          </button>
        </div>
      ) : viewMode === 'matrix' ? (
        renderMatrix()
      ) : (
        renderList()
      )}

      {/* Create Modal */}
      {createModalOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold text-slate-900 mb-4">Neues Risiko</h3>
            {renderForm(true)}
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => setCreateModalOpen(false)}
                className="px-4 py-2 text-slate-600 hover:text-slate-800"
              >
                Abbrechen
              </button>
              <button
                onClick={handleCreate}
                className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
              >
                Erstellen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Modal */}
      {editModalOpen && selectedRisk && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold text-slate-900 mb-4">
              Risiko bearbeiten: {selectedRisk.risk_id}
            </h3>
            {renderForm(false)}
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => setEditModalOpen(false)}
                className="px-4 py-2 text-slate-600 hover:text-slate-800"
              >
                Abbrechen
              </button>
              <button
                onClick={handleUpdate}
                className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
              >
                Speichern
              </button>
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  )
}
