import { Box, Chip, IconButton, Typography } from '@mui/material'
import { X } from 'lucide-react'
import { useRemoveFromShortlist } from '../../hooks/useShortlists'
import { useToastStore } from '../../stores/toastStore'
import type { ShortlistItem } from '../../domain/shortlist'

const RESULT_TYPE_LABEL: Record<string, string> = {
  VERIFIED_PORTFOLIO: 'Portfolio',
  EXTERNAL_MARKET: 'Markt',
  FUTURE_AVAILABILITY: 'Signal',
}

const SCORE_COLOR = (s: number) => s >= 75 ? '#1a7a4a' : s >= 55 ? '#d97706' : '#c0392b'

interface Props {
  item: ShortlistItem
  shortlistId: string
  isFinalized: boolean
}

export function ShortlistItemCard({ item, shortlistId, isFinalized }: Props) {
  const removeItem = useRemoveFromShortlist()
  const showToast = useToastStore((s) => s.showToast)

  const addedDate = new Date(item.addedAt).toLocaleDateString('de-CH', { day: '2-digit', month: '2-digit', year: 'numeric' })

  return (
    <Box sx={{
      p: 2,
      borderBottom: '1px solid #f1f5f9',
      opacity: isFinalized ? 0.75 : 1,
      display: 'flex',
      gap: 1.5,
      alignItems: 'flex-start',
    }}>
      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
          <Typography variant="body2" sx={{ fontWeight: 600 }}>{item.title}</Typography>
          <Chip
            label={RESULT_TYPE_LABEL[item.resultType] ?? item.resultType}
            size="small"
            sx={{ fontSize: 10, height: 18 }}
          />
          <Chip
            label={`${item.matchScore}`}
            size="small"
            sx={{ bgcolor: SCORE_COLOR(item.matchScore), color: 'white', fontSize: 10, height: 18, fontWeight: 700 }}
          />
        </Box>
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
          {item.sourceLabel ?? item.resultType} · {item.addedBy} · {addedDate}
        </Typography>
        {item.note && (
          <Typography variant="caption" sx={{ display: 'block', mt: 0.5, color: '#475569', fontStyle: 'italic' }}>
            {item.note}
          </Typography>
        )}
      </Box>
      {!isFinalized && (
        <IconButton
          size="small"
          disabled={removeItem.isPending}
          onClick={() => removeItem.mutate(
            { shortlistId, resultId: item.resultId },
            {
              onSuccess: () => showToast('Objekt aus Shortlist entfernt.'),
              onError: () => showToast('Entfernen fehlgeschlagen.', 'error'),
            }
          )}
          sx={{ color: '#94a3b8', '&:hover': { color: '#c0392b' }, flexShrink: 0 }}
        >
          <X size={14} />
        </IconButton>
      )}
    </Box>
  )
}
