import { Box, Typography } from '@mui/material'
import { AssistantActionCards } from './AssistantActionCards'
import type { AssistantMessage } from '../../domain/assistant'

function MessageBubble({ message }: { message: AssistantMessage }) {
  const isUser = message.role === 'user'

  return (
    <Box sx={{ display: 'flex', flexDirection: isUser ? 'row-reverse' : 'row', gap: 1, px: 2, py: 0.75, alignItems: 'flex-start' }}>
      {!isUser && (
        <Box
          sx={{
            width: 28, height: 28, borderRadius: '50%', bgcolor: '#4f46e5',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, mt: 0.25,
          }}
        >
          <Typography variant="caption" sx={{ color: 'white', fontWeight: 700, fontSize: '0.625rem' }}>AI</Typography>
        </Box>
      )}

      <Box sx={{ maxWidth: '80%', minWidth: 0 }}>
        {/* Bubble */}
        <Box
          sx={{
            px: 1.5,
            py: 1,
            borderRadius: isUser ? '8px 8px 2px 8px' : '2px 8px 8px 8px',
            bgcolor: isUser ? '#1e3a5f' : '#f1f5f9',
            color: isUser ? 'white' : '#1e293b',
          }}
        >
          <Typography
            variant="body2"
            sx={{
              fontSize: '0.8125rem',
              lineHeight: 1.6,
              whiteSpace: 'pre-wrap',
              color: 'inherit',
              '& strong': { fontWeight: 700 },
            }}
            dangerouslySetInnerHTML={{
              __html: message.content
                .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
                .replace(/\n/g, '<br/>'),
            }}
          />
        </Box>

        {/* Metadata */}
        {!isUser && (message.confidence !== undefined || (message.sources && message.sources.length > 0)) && (
          <Box sx={{ display: 'flex', gap: 0.75, mt: 0.5, flexWrap: 'wrap', alignItems: 'center' }}>
            {message.confidence !== undefined && (
              <Typography variant="caption" sx={{ fontSize: '0.65rem', color: '#94a3b8' }}>
                Konfidenz: {Math.round(message.confidence * 100)}%
              </Typography>
            )}
            {message.sources?.map(s => (
              <Typography key={s} variant="caption" sx={{ fontSize: '0.65rem', color: '#94a3b8', bgcolor: '#f8fafc', px: 0.5, py: 0.125, borderRadius: 0.5, border: '1px solid #e2e8f0' }}>
                {s}
              </Typography>
            ))}
          </Box>
        )}

        {/* Timestamp */}
        <Typography variant="caption" sx={{ display: 'block', fontSize: '0.6rem', color: '#cbd5e1', mt: 0.25, textAlign: isUser ? 'right' : 'left' }}>
          {new Date(message.createdAt).toLocaleTimeString('de-CH', { timeStyle: 'short' })}
        </Typography>
      </Box>
    </Box>
  )
}

interface Props {
  messages: AssistantMessage[]
}

export function AssistantMessageList({ messages }: Props) {
  return (
    <Box>
      {messages.map((msg) => (
        <Box key={msg.id}>
          <MessageBubble message={msg} />
          {msg.role === 'assistant' && msg.actions && msg.actions.length > 0 && (
            <AssistantActionCards actions={msg.actions} />
          )}
        </Box>
      ))}
    </Box>
  )
}
