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

const IMPORTANCE_ORDER = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']
const IMPORTANCE_META: Record<string, { label: string; color: 'error' | 'warning' | 'default' }> = {
  CRITICAL: { label: 'Kritisch',  color: 'error' },
  HIGH:     { label: 'Wichtig',   color: 'warning' },
  MEDIUM:   { label: 'Optional',  color: 'default' },
  LOW:      { label: 'Optional',  color: 'default' },
}

interface MissingItemRowProps {
  item: MissingDataItem
}

function MissingItemRow({ item }: MissingItemRowProps) {
  const meta = IMPORTANCE_META[item.importance] ?? IMPORTANCE_META.LOW

  return (
    <Box sx={{ p: 1.5, border: '1px solid #e2e8f0', borderRadius: 1, mb: 1 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
        <FileQuestion size={14} color="#64748b" />
        <Typography variant="body2" sx={{ fontWeight: 600, flex: 1 }}>{item.field}</Typography>
        <Chip label={meta.label} size="small" color={meta.color} variant="outlined" />
      </Box>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>
        {item.description}
      </Typography>
      <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1, fontStyle: 'italic' }}>
        Auswirkung: {item.impact}
      </Typography>
      <Box sx={{ display: 'flex', gap: 0.75 }}>
        <Button size="small" variant="outlined" sx={{ fontSize: 11, py: 0.25 }}>
          Daten anfordern
        </Button>
        <Button size="small" variant="text" sx={{ fontSize: 11, py: 0.25, color: '#64748b' }}>
          Nicht relevant
        </Button>
        <Button size="small" variant="text" sx={{ fontSize: 11, py: 0.25, color: '#64748b' }}>
          Zur Prüfung
        </Button>
      </Box>
    </Box>
  )
}

interface Props {
  match: Match
}

export function MissingInformationPanel({ match }: Props) {
  const missingData: MissingDataItem[] = match.missingData ?? []
  if (missingData.length === 0) return null

  const sorted = [...missingData].sort(
    (a, b) => IMPORTANCE_ORDER.indexOf(a.importance) - IMPORTANCE_ORDER.indexOf(b.importance)
  )

  return (
    <Paper sx={{ p: 2.5, mb: 2 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1.5 }}>
        <Typography variant="h6" sx={{ fontWeight: 700 }}>Fehlende Informationen</Typography>
        <Chip
          label={`${missingData.length} fehlend`}
          size="small"
          color={missingData.some(m => m.importance === 'CRITICAL') ? 'error' : 'warning'}
        />
      </Box>
      {sorted.map((item, i) => (
        <MissingItemRow key={i} item={item} />
      ))}
    </Paper>
  )
}
