import { Box, Chip, Link, Typography } from '@mui/material'
import { FileText, Globe, PenLine, FileArchive } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import type { SignalEvidence } from '../../domain/marketSignal'
import { EvidenceType } from '../../domain/marketSignal'

const EVIDENCE_ICONS: Record<string, LucideIcon> = {
  [EvidenceType.TEXT_EXCERPT]: FileText,
  [EvidenceType.URL_REFERENCE]: Globe,
  [EvidenceType.ANALYST_NOTE]: PenLine,
  [EvidenceType.DOCUMENT]: FileArchive,
}

const EVIDENCE_LABELS: Record<string, string> = {
  [EvidenceType.TEXT_EXCERPT]: 'Textauszug',
  [EvidenceType.URL_REFERENCE]: 'URL-Referenz',
  [EvidenceType.ANALYST_NOTE]: 'Analyst-Notiz',
  [EvidenceType.DOCUMENT]: 'Dokument',
}

function formatDate(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',
  })
}

interface SignalEvidenceListProps {
  evidence: SignalEvidence[]
}

export function SignalEvidenceList({ evidence }: SignalEvidenceListProps) {
  if (evidence.length === 0) {
    return (
      <Typography variant="body2" sx={{ color: 'text.secondary', fontStyle: 'italic' }}>
        Keine Evidenz vorhanden.
      </Typography>
    )
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
      {evidence.map((ev) => {
        const Icon = EVIDENCE_ICONS[ev.evidenceType] ?? FileText
        return (
          <Box
            key={ev.id}
            sx={{
              p: 1.5,
              bgcolor: '#f8fafc',
              borderRadius: 1,
              border: '1px solid #e2e8f0',
            }}
          >
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.75 }}>
              <Icon size={14} color="#64748b" />
              <Typography sx={{ fontSize: '0.7rem', color: '#64748b', fontWeight: 600 }}>
                {EVIDENCE_LABELS[ev.evidenceType]}
              </Typography>
              <Chip
                size="small"
                label={`${Math.round(ev.confidence * 100)}%`}
                sx={{ bgcolor: 'rgba(99,102,241,0.1)', color: '#4f46e5', border: 'none', fontSize: '0.65rem', height: 18, ml: 'auto' }}
              />
            </Box>

            <Typography variant="body2" sx={{ color: '#1e293b', lineHeight: 1.5, mb: ev.sourceUrl ? 0.75 : 0 }}>
              {ev.content}
            </Typography>

            {ev.sourceUrl && (
              <Link
                href={ev.sourceUrl}
                target="_blank"
                rel="noopener noreferrer"
                sx={{ fontSize: '0.7rem', display: 'block' }}
              >
                {ev.sourceUrl}
              </Link>
            )}

            <Typography sx={{ fontSize: '0.65rem', color: '#94a3b8', mt: 0.5 }}>
              Abgerufen: {formatDate(ev.retrievedAt)}
            </Typography>
          </Box>
        )
      })}
    </Box>
  )
}
