import { memo } from 'react'
import { Box, Chip, LinearProgress, Tooltip, Typography } from '@mui/material'
import { MapPin } from 'lucide-react'
import { getAssetTypeColor, getAssetTypeLabel } from './propertyHelpers'
import { DS_TEXT, DS_BORDER } from '../../lib/ds'
import type { Property } from '../../domain/property'

interface Props {
  property: Property
  onSelect: (id: string) => void
  inquiryCount?: number
}

// Occupancy status — colour only for actionable exceptions; occupied = expected, no signal needed
const STATUS_CONFIG = {
  AVAILABLE_NOW:  { dot: '#b91c1c', text: '#b91c1c', label: 'Verfügbar' },
  AVAILABLE_SOON: { dot: '#a16207', text: '#a16207', label: 'Bald frei' },
  OCCUPIED:       { dot: '#9a9a9a', text: '#9a9a9a', label: 'Vermietet' },
  FUTURE_SIGNAL:  { dot: '#5b3f8a', text: '#5b3f8a', label: 'Geplante Verf.' },
} as const

const FIT_OUT_META: Record<string, { label: string; tip: string }> = {
  SHELL:   { label: 'Rohbau',         tip: 'Keine Einbauten — volle Ausbauinvestition.' },
  BASIC:   { label: 'Grundausbau',    tip: 'Grundinfrastruktur vorhanden.' },
  FULL:    { label: 'Vollausbau',     tip: 'Bezugsfertig ausgebaut.' },
  PREMIUM: { label: 'Premium-Ausbau', tip: 'Hochwertig, sofort bezugsfertig.' },
}

export const PropertyIntelligenceCard = memo(function PropertyIntelligenceCard({ property: p, onSelect, inquiryCount }: Props) {
  const confPct = Math.round(p.confidenceScore * 100)
  const assetColor = getAssetTypeColor(p.assetType)
  const hasImage = !!p.images?.[0]
  const hasInquiries = (inquiryCount ?? 0) > 0

  const statusKey = p.availabilityStatus as keyof typeof STATUS_CONFIG
  const status = STATUS_CONFIG[statusKey] ?? STATUS_CONFIG.OCCUPIED

  const availDate = p.availabilityDate
    ? new Date(p.availabilityDate).toLocaleDateString('de-CH', { month: 'short', year: '2-digit' })
    : null

  return (
    <Box
      onClick={() => onSelect(p.id)}
      sx={{
        borderRadius: 2,
        overflow: 'hidden',
        border: `1px solid ${DS_BORDER.default}`,
        bgcolor: '#ffffff',
        display: 'flex',
        flexDirection: 'column',
        cursor: 'pointer',
        position: 'relative',
        zIndex: 0,
        transition: 'transform 0.18s ease, box-shadow 0.18s ease, border-color 0.15s',
        '&:hover': {
          borderColor: '#b0aead',
          transform: 'scale(1.025)',
          boxShadow: '0 10px 32px rgba(0,0,0,0.13)',
          zIndex: 1,
        },
      }}
    >
      {/* ── Image — clean, no text overlay ── */}
      <Box sx={{ position: 'relative', aspectRatio: '15/8', flexShrink: 0, bgcolor: '#f4f3f0', overflow: 'hidden' }}>
        {hasImage ? (
          <Box component="img" src={p.images![0]} alt={p.title}
            sx={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        ) : (
          <Box sx={{
            width: '100%', height: '100%',
            background: `linear-gradient(135deg, ${assetColor}18 0%, ${assetColor}30 100%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Typography sx={{ fontSize: '2.5rem', opacity: 0.2 }}>🏢</Typography>
          </Box>
        )}

        {/* Single neutral asset-type label */}
        <Box sx={{ position: 'absolute', top: 10, left: 10, bgcolor: 'rgba(0,0,0,0.50)', borderRadius: '3px', px: 0.75, py: 0.25 }}>
          <Typography sx={{ fontSize: '0.65rem', fontWeight: 600, color: 'white', lineHeight: 1.3 }}>
            {getAssetTypeLabel(p.assetType)}
          </Typography>
        </Box>
      </Box>

      {/* ── Body ── */}
      <Box sx={{ px: 2.5, pt: 2.25, pb: 2.5, display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>

        {/* Title + location + status inline */}
        <Box>
          <Typography sx={{ fontWeight: 600, fontSize: '1.0625rem', color: DS_TEXT.primary, lineHeight: 1.3 }} noWrap>
            {p.title}
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 0.6 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.4 }}>
              <MapPin size={12} color="#9a9a9a" />
              <Typography sx={{ fontSize: '0.8125rem', color: DS_TEXT.muted }}>
                {p.location.city}{p.location.district ? ` · ${p.location.district}` : ''}
              </Typography>
            </Box>
            {/* Status — plain dot + text, no pill container */}
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <Box sx={{ width: 7, height: 7, borderRadius: '50%', bgcolor: status.dot, flexShrink: 0 }} />
              <Typography sx={{ fontSize: '0.8rem', fontWeight: 500, color: status.text, lineHeight: 1 }}>
                {status.label}
                {p.availabilityStatus === 'AVAILABLE_SOON' && availDate ? ` · ab ${availDate}` : ''}
              </Typography>
            </Box>
          </Box>
        </Box>

        {/* 3 key metrics — no boxes, whitespace only */}
        <Box sx={{ display: 'flex', gap: 2.5 }}>
          <Box>
            <Typography sx={{ fontSize: '0.75rem', color: DS_TEXT.muted, mb: 0.35 }}>Fläche</Typography>
            <Typography sx={{ fontWeight: 600, fontSize: '1rem', color: DS_TEXT.primary }}>
              {p.areaSqm.toLocaleString('de-CH')} m²
            </Typography>
          </Box>

          <Box>
            <Typography sx={{ fontSize: '0.75rem', color: DS_TEXT.muted, mb: 0.35 }}>Miete</Typography>
            <Typography sx={{ fontWeight: 600, fontSize: '1rem', color: DS_TEXT.primary }}>
              {p.rentPricePerSqm}
              <Typography component="span" sx={{ fontSize: '0.7rem', fontWeight: 400, color: DS_TEXT.muted }}> CHF/m²/J</Typography>
            </Typography>
          </Box>

          <Tooltip title={hasInquiries ? `${inquiryCount} aktive Anfragen` : 'Noch keine Anfragen'} placement="top" arrow>
            <Box>
              <Typography sx={{ fontSize: '0.75rem', color: DS_TEXT.muted, mb: 0.35 }}>Anfragen</Typography>
              <Typography sx={{ fontWeight: 600, fontSize: '1rem', color: hasInquiries ? '#a16207' : DS_TEXT.muted }}>
                {inquiryCount ?? 0}
              </Typography>
            </Box>
          </Tooltip>
        </Box>

        {/* Chips + Datenvollständigkeit in einer Zeile */}
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 1, mt: 'auto' }}>
          <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', alignItems: 'center' }}>
            {p.hardFacts?.fitOut && (() => {
              const meta = FIT_OUT_META[p.hardFacts!.fitOut!] ?? { label: p.hardFacts!.fitOut!, tip: '' }
              return (
                <Tooltip title={meta.tip} placement="top" arrow>
                  <Chip label={meta.label} size="small"
                    sx={{ height: 22, fontSize: '0.73rem', bgcolor: '#f4f3f0', color: DS_TEXT.secondary, border: `1px solid ${DS_BORDER.default}`, cursor: 'help' }} />
                </Tooltip>
              )
            })()}
            {p.contractDurationMonths && (
              <Chip label={`${p.contractDurationMonths}M Vertrag`} size="small"
                sx={{ height: 22, fontSize: '0.73rem', bgcolor: '#f4f3f0', color: DS_TEXT.secondary, border: `1px solid ${DS_BORDER.default}` }} />
            )}
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexShrink: 0 }}>
            <Typography sx={{ fontSize: '0.68rem', color: DS_TEXT.disabled }}>Daten</Typography>
            <LinearProgress variant="determinate" value={confPct}
              sx={{ width: 44, height: 3, borderRadius: 1, bgcolor: '#f4f3f0',
                '& .MuiLinearProgress-bar': { bgcolor: '#152642', borderRadius: 1 } }} />
            <Typography sx={{ fontSize: '0.78rem', fontWeight: 700, color: p.confidenceScore >= 0.75 ? '#b8975a' : DS_TEXT.muted }}>
              {confPct}%
            </Typography>
          </Box>
        </Box>
      </Box>
    </Box>
  )
})
