import { memo } from 'react'
import { Alert, Box, Button, Chip, Typography } from '@mui/material'
import { MapPin, AlertTriangle } from 'lucide-react'
import { useSessionStore } from '../../stores/sessionStore'
import { useInquiryStore } from '../../stores/inquiryStore'
import { HeatBadge } from '../shared/HeatBadge'
import { getScoreTier, SCORE_THEME } from '../shared/scoreTheme'
import { RESULT_TYPE_META, DS_TEXT, DS_BORDER } from '../../lib/ds'
import { confidenceHex } from '../../lib/utils'
import { MatchCardRestrictedState } from './MatchCardRestrictedState'
import type { MatchCardViewModel } from './MatchCardViewModel'

interface Props {
  vm: MatchCardViewModel
  imageUrl?: string
}

export const MatchCardCompact = memo(function MatchCardCompact({ vm, imageUrl }: Props) {
  if (vm.isRestricted) return <MatchCardRestrictedState />

  const { currentUser } = useSessionStore()
  const openInquiryDialog = useInquiryStore(s => s.openInquiryDialog)
  const isPortfolioOwner = currentUser?.role === 'PROPERTY_MANAGER' || currentUser?.role === 'ORGANIZATION_ADMIN'

  const tier = getScoreTier(vm.matchScore)
  const scoreBadgeBg = SCORE_THEME[tier].gradient
  const rt = RESULT_TYPE_META[vm.resultType] ?? { label: vm.resultType, color: '#9a9a9a' }
  const confPct = Math.round(vm.confidenceScore * 100)
  const topRisk = vm.risks.find(r => r.level === 'CRITICAL' || r.level === 'HIGH')

  const leftAccent = vm.isCompareSelected ? '#5b3f8a' : vm.isSelected ? '#152642' : 'transparent'

  // Compact metric line — area · rent · availability
  const metricParts: string[] = []
  if (vm.areaSqm) metricParts.push(`${vm.areaSqm.toLocaleString('de-CH')} m²`)
  if (vm.rentPerSqm) metricParts.push(`CHF ${vm.rentPerSqm}/m²/J`)
  if (vm.availabilityLabel) metricParts.push(vm.availabilityLabel)
  const metricLine = metricParts.join('  ·  ')

  // Detail action — prefer the "Details →" action if available, fallback to first action
  const detailAction = vm.actions.find(a => a.actionType === 'OPEN_DETAIL' && a.label.includes('Detail'))
    ?? vm.actions.find(a => a.actionType === 'OPEN_DETAIL')

  return (
    <Box sx={{
      display: 'flex',
      borderRadius: 2,
      overflow: 'hidden',
      border: `1px solid ${DS_BORDER.default}`,
      borderLeft: `3px solid ${leftAccent}`,
      bgcolor: '#ffffff',
      boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
      opacity: vm.isStaleData ? 0.75 : 1,
      transition: 'border-color 0.15s, transform 0.18s ease, box-shadow 0.18s ease',
      position: 'relative',
      zIndex: 0,
      '&:hover': {
        borderColor: '#b0aead',
        transform: 'scale(1.012)',
        boxShadow: '0 6px 20px rgba(0,0,0,0.10)',
        zIndex: 1,
      },
    }}>

      {/* ── Image strip — 180px, Ginesta proportion ── */}
      <Box sx={{ width: 180, flexShrink: 0, position: 'relative', bgcolor: '#f4f3f0' }}>
        {imageUrl ? (
          <img
            src={imageUrl}
            alt=""
            style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          />
        ) : (
          <Box sx={{
            width: '100%', height: '100%', minHeight: 140,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            bgcolor: '#f4f3f0',
          }}>
            <MapPin size={24} color="#c4c4c4" />
          </Box>
        )}

        {/* Score badge — top left */}
        <Box sx={{
          position: 'absolute', top: 8, left: 8,
          bgcolor: scoreBadgeBg, borderRadius: '6px',
          px: 0.875, py: 0.25,
          border: `1px solid ${SCORE_THEME[tier].border}`,
        }}>
          <Typography sx={{
            fontWeight: 700, fontSize: '1.125rem',
            color: '#ffffff', lineHeight: 1, letterSpacing: '-0.01em',
          }}>
            {vm.matchScore}%
          </Typography>
        </Box>

        {/* Location pill — Ginesta-style, top right */}
        <Box sx={{
          position: 'absolute', top: 8, right: 8,
          bgcolor: 'rgba(255,255,255,0.92)',
          borderRadius: '20px',
          px: 1, py: 0.35,
          display: 'flex', alignItems: 'center', gap: 0.4,
          backdropFilter: 'blur(4px)',
        }}>
          <MapPin size={9} color="#64748b" />
          <Typography sx={{ fontSize: '0.65rem', fontWeight: 500, color: '#374151', lineHeight: 1 }}>
            {vm.locationLabel}
          </Typography>
        </Box>
      </Box>

      {/* ── Content ── */}
      <Box sx={{ flex: 1, px: 2, py: 2.5, display: 'flex', flexDirection: 'column', minWidth: 0 }}>

        {vm.disclaimer && (
          <Alert severity="warning" sx={{ mb: 1, py: 0.25, fontSize: '0.72rem' }}>{vm.disclaimer}</Alert>
        )}

        {/* Chips — result type + heat + confidence */}
        <Box sx={{ display: 'flex', gap: 0.5, alignItems: 'center', mb: 0.875 }}>
          <Chip label={rt.label} size="small"
            sx={{ bgcolor: rt.color, color: 'white', fontWeight: 600, fontSize: 10, height: 20 }} />
          <HeatBadge propertyId={vm.propertyId} size="sm" />
          <Chip label={`${confPct}% Konfidenz`} size="small"
            sx={{ bgcolor: confidenceHex(vm.confidenceScore), color: 'white', fontSize: 10, height: 20 }} />
          {vm.resultType === 'VERIFIED_PORTFOLIO' && isPortfolioOwner && (
            <Chip label="Ihr Objekt" size="small"
              sx={{ bgcolor: 'rgba(21,38,66,0.10)', color: '#152642', fontWeight: 700, fontSize: 9, height: 18 }} />
          )}
        </Box>

        {/* Title */}
        <Typography variant="subtitle2" sx={{ fontWeight: 700, lineHeight: 1.3, color: DS_TEXT.primary }} noWrap>
          {vm.title}
        </Typography>
        {vm.propertySubtitle && (
          <Typography variant="caption" sx={{ color: DS_TEXT.secondary, fontWeight: 500, display: 'block', mt: 0.1 }} noWrap>
            {vm.propertySubtitle}
          </Typography>
        )}

        {/* Metric line — Ginesta-style */}
        {metricLine && (
          <Typography sx={{ fontSize: '0.75rem', color: '#94a3b8', mt: 0.5, letterSpacing: 0.1 }}>
            {metricLine}
          </Typography>
        )}

        {/* Explainability summary — 1 line */}
        {vm.explainabilitySummary && (
          <Typography variant="body2" sx={{
            color: DS_TEXT.secondary, fontWeight: 500, mt: 0.875, lineHeight: 1.5,
            overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical',
          }}>
            {vm.explainabilitySummary}
          </Typography>
        )}

        {/* Critical risk only */}
        {topRisk && topRisk.level === 'CRITICAL' && (
          <Alert icon={<AlertTriangle size={13} />} severity="error"
            sx={{ mt: 0.75, py: 0.25, fontSize: '0.72rem' }}>
            {topRisk.description}
          </Alert>
        )}

        {/* 2 Buttons — Anfrage + Details */}
        <Box sx={{ display: 'flex', gap: 0.625, mt: 'auto', pt: 1.25 }}>
          <Button
            size="small"
            variant="contained"
            onClick={e => {
              e.stopPropagation()
              openInquiryDialog({
                propertyTitle: vm.title,
                location: vm.locationLabel ?? '',
                matchScore: vm.matchScore,
                matchId: vm.id,
                propertyId: vm.propertyId,
              })
            }}
            sx={{ textTransform: 'none', fontSize: '0.7rem', py: 0.375, px: 1, bgcolor: '#152642', '&:hover': { bgcolor: '#0e1c30' } }}
          >
            Anfrage
          </Button>
          {detailAction && (
            <Button
              size="small"
              variant="outlined"
              onClick={detailAction.onClick}
              sx={{ textTransform: 'none', fontSize: '0.7rem', py: 0.375, px: 1 }}
            >
              Details →
            </Button>
          )}
        </Box>
      </Box>
    </Box>
  )
})
