import { Box, Chip, Typography } from '@mui/material'
import { Kanban } from 'lucide-react'
import { INQUIRY_STATUS_META, DS_COLORS, DS_TEXT, DS_BG, DS_BORDER } from '../../lib/ds'
import type { Inquiry } from '../../domain/inquiry'

interface AnfragenInquiryItemProps {
  inq: Inquiry
  isSelected: boolean
  hasPipeline: boolean
  perspective?: 'demand' | 'supply'
  onSelect: (id: string) => void
}

export function AnfragenInquiryItem({ inq, isSelected, hasPipeline, perspective = 'supply', onSelect }: AnfragenInquiryItemProps) {
  const cfg = INQUIRY_STATUS_META[inq.status ?? 'new']
  const displayDate = new Date(inq.updatedAt).toLocaleDateString('de-CH', { day: '2-digit', month: '2-digit' })
  const lastMsg = inq.thread[inq.thread.length - 1]
  const unreadColor = cfg?.fg ?? DS_TEXT.danger

  const primaryTitle = perspective === 'demand'
    ? (inq.propertyAddress ?? inq.subject)
    : inq.tenantName

  const secondaryLine = perspective === 'demand'
    ? (inq.propertyManagerCompany ?? inq.propertyManagerName ?? '')
    : (inq.tenantCompany ?? '')

  const lastMsgPrefix = (() => {
    if (!lastMsg) return ''
    if (perspective === 'demand') {
      return lastMsg.senderType === 'tenant'
        ? 'Sie: '
        : `${inq.propertyManagerName ?? 'Verwalter'}: `
    }
    return lastMsg.senderType === 'tenant' ? 'Sie: ' : `${lastMsg.senderName}: `
  })()

  return (
    <Box onClick={() => onSelect(inq.id)} sx={{
      px: 2, py: 1.5,
      borderBottom: `1px solid ${DS_BORDER.muted}`,
      cursor: 'pointer',
      bgcolor: isSelected ? DS_COLORS.futureCard.signal.headerBg : !inq.isRead ? 'rgba(220,38,38,0.03)' : 'transparent',
      borderLeft: isSelected ? '3px solid' : '3px solid transparent',
      borderLeftColor: isSelected ? 'primary.main' : 'transparent',
      '&:hover': { bgcolor: isSelected ? DS_COLORS.futureCard.signal.headerBg : DS_BG.page },
      transition: 'background-color 0.1s ease',
    }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 0.375 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, minWidth: 0 }}>
          {!inq.isRead && <Box sx={{ width: 7, height: 7, borderRadius: '50%', bgcolor: unreadColor, flexShrink: 0 }} />}
          <Typography variant="body2" sx={{ fontWeight: !inq.isRead ? 700 : 500, fontSize: '0.8125rem' }} noWrap>
            {primaryTitle}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flexShrink: 0 }}>
          {inq.unreadCount > 0 && (
            <Box sx={{ width: 18, height: 18, borderRadius: '50%', bgcolor: unreadColor, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Typography sx={{ color: 'white', fontSize: '0.6rem', fontWeight: 700 }}>{inq.unreadCount}</Typography>
            </Box>
          )}
          <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.7rem' }}>{displayDate}</Typography>
        </Box>
      </Box>
      {secondaryLine && (
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', fontSize: '0.7rem', mb: 0.25 }} noWrap>
          {secondaryLine}
        </Typography>
      )}
      <Typography variant="caption" sx={{ color: DS_TEXT.secondary, display: 'block', mb: 0.5, fontWeight: !inq.isRead ? 600 : 400, fontSize: '0.75rem' }} noWrap>
        {inq.subject}
      </Typography>
      {lastMsg && (
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5, fontSize: '0.7rem' }} noWrap>
          {lastMsgPrefix}
          {lastMsg.body.split('\n')[0]}
        </Typography>
      )}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Chip label={cfg?.label ?? inq.status} size="small"
          sx={{ height: 16, fontSize: '0.6rem', bgcolor: cfg?.bg, color: cfg?.fg, fontWeight: 600 }} />
        {inq.matchScore && (
          <Typography variant="caption" sx={{ color: inq.matchScore >= 80 ? DS_TEXT.success : DS_TEXT.warning, fontWeight: 700, fontSize: '0.7rem' }}>
            {inq.matchScore}%
          </Typography>
        )}
        {hasPipeline && (
          <Chip
            icon={<Kanban size={9} />}
            label="Pipeline"
            size="small"
            sx={{
              height: 16, fontSize: '0.6rem', fontWeight: 600,
              bgcolor: DS_COLORS.futureCard.signal.headerBg,
              color: 'primary.main',
              '& .MuiChip-icon': { color: 'primary.main' },
            }}
          />
        )}
      </Box>
    </Box>
  )
}
