import { Box, Chip, Paper, Typography } from '@mui/material'
import { ShieldAlert } from 'lucide-react'
import type { Match } from '../../domain/match'
import type { Risk } from '../../domain/match'

const LEVEL_ORDER = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']
const LEVEL_META: Record<string, { label: string; color: 'error' | 'warning' | 'success'; bgcolor: string; border: string }> = {
  CRITICAL: { label: 'Kritisch',   color: 'error',   bgcolor: '#fef2f2', border: '#fca5a5' },
  HIGH:     { label: 'Hoch',       color: 'error',   bgcolor: '#fff7ed', border: '#fed7aa' },
  MEDIUM:   { label: 'Mittel',     color: 'warning', bgcolor: '#fffbeb', border: '#fde68a' },
  LOW:      { label: 'Gering',     color: 'success', bgcolor: '#f0fdf4', border: '#bbf7d0' },
}

interface Props {
  match: Match
}

export function RiskPanel({ match }: Props) {
  const risks: Risk[] = match.risks ?? []
  if (risks.length === 0) return null

  const sorted = [...risks].sort(
    (a, b) => LEVEL_ORDER.indexOf(a.level) - LEVEL_ORDER.indexOf(b.level)
  )

  return (
    <Paper sx={{ p: 2.5, mb: 2 }}>
      <Typography variant="h6" sx={{ fontWeight: 700, mb: 1.5 }}>Risiken & Unsicherheiten</Typography>
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.25 }}>
        {sorted.map((r, i) => {
          const meta = LEVEL_META[r.level] ?? LEVEL_META.LOW
          return (
            <Box
              key={i}
              sx={{ p: 1.5, bgcolor: meta.bgcolor, border: `1px solid ${meta.border}`, borderRadius: 1 }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                <ShieldAlert size={15} color={meta.color === 'error' ? '#dc2626' : '#d97706'} />
                <Typography variant="body2" sx={{ fontWeight: 600, flex: 1 }}>{r.category}</Typography>
                <Chip label={meta.label} size="small" color={meta.color} />
              </Box>
              <Typography variant="body2" color="text.secondary" sx={{ mb: r.mitigation ? 0.5 : 0 }}>
                {r.description}
              </Typography>
              {r.mitigation && (
                <Typography variant="caption" color="text.secondary" sx={{ fontStyle: 'italic' }}>
                  → {r.mitigation}
                </Typography>
              )}
            </Box>
          )
        })}
      </Box>
    </Paper>
  )
}
