import { Box, Typography } from '@mui/material'
import type { AuditTrailEntry } from '../../domain/signalPipeline'
import { PIPELINE_STAGE_ORDER } from '../../domain/signalPipeline'

interface SignalToMatchAuditTrailProps {
  entries: AuditTrailEntry[]
}

function getStageColor(entry: AuditTrailEntry): string {
  const idx = PIPELINE_STAGE_ORDER.indexOf(entry.stage)
  if (idx <= 0) return '#94a3b8'
  if (idx >= 5) return '#15803d'
  if (idx >= 3) return '#152642'
  if (idx >= 2) return '#4f46e5'
  return '#2563eb'
}

function formatTimestamp(iso: string): string {
  return new Date(iso).toLocaleString('de-CH', {
    day: '2-digit',
    month: '2-digit',
    year: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

export function SignalToMatchAuditTrail({ entries }: SignalToMatchAuditTrailProps) {
  if (entries.length === 0) {
    return (
      <Typography variant="caption" sx={{ color: 'text.secondary' }}>
        Keine Audit-Einträge vorhanden.
      </Typography>
    )
  }

  return (
    <Box>
      {entries.map((entry, idx) => {
        const isLast = idx === entries.length - 1
        const dotColor = getStageColor(entry)

        return (
          <Box key={entry.id} sx={{ display: 'flex', gap: 1.5, mb: 1.5 }}>
            {/* Timeline column */}
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
              <Box
                sx={{
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  bgcolor: dotColor,
                  mt: 0.25,
                  flexShrink: 0,
                }}
              />
              {!isLast && (
                <Box
                  sx={{
                    width: 2,
                    flex: 1,
                    minHeight: 16,
                    bgcolor: 'rgba(148,163,184,0.3)',
                    mt: 0.5,
                  }}
                />
              )}
            </Box>

            {/* Content column */}
            <Box sx={{ flex: 1, pb: isLast ? 0 : 0.5 }}>
              <Typography variant="caption" sx={{ fontWeight: 600, display: 'block', lineHeight: 1.4 }}>
                {entry.action}
              </Typography>
              <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', lineHeight: 1.4 }}>
                {entry.performedBy} · {formatTimestamp(entry.timestamp)}
              </Typography>
              <Typography
                variant="caption"
                sx={{ color: '#64748b', display: 'block', lineHeight: 1.4, mt: 0.25 }}
              >
                {entry.details}
              </Typography>
            </Box>
          </Box>
        )
      })}
    </Box>
  )
}
