import { Box, Button, Chip, Typography } from '@mui/material'
import { Building2, CheckCircle2, MapPin } from 'lucide-react'
import { useSessionStore } from '../../stores/sessionStore'
import { useInquiryStore } from '../../stores/inquiryStore'
import { LocationPreview } from '../shared/LocationPreview'
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 type { MatchCardViewModel } from './MatchCardViewModel'
import { FutureAvailabilityCard } from './FutureAvailabilityCard'

interface Props {
  vm: MatchCardViewModel
  imageUrl?: string
  lat?: number
  lng?: number
  cityLabel?: string
  overlayTypeLabel?: string
  overlayLocationLabel?: string
}

export function IntelligenceMatchCard({ vm, imageUrl, lat, lng, cityLabel, overlayTypeLabel, overlayLocationLabel }: Props) {
  const tier = getScoreTier(vm.matchScore)
  const theme = SCORE_THEME[tier]
  const { currentUser } = useSessionStore()
  const openInquiryDialog = useInquiryStore(s => s.openInquiryDialog)
  const isPortfolioOwner = currentUser?.role === 'PROPERTY_MANAGER' || currentUser?.role === 'ORGANIZATION_ADMIN'
  const rt = RESULT_TYPE_META[vm.resultType] ?? { label: vm.resultType, color: '#9a9a9a' }
  const isFuture = vm.resultType === 'FUTURE_AVAILABILITY'
  const confPct = Math.round(vm.confidenceScore * 100)

  if (isFuture) {
    return <FutureAvailabilityCard vm={vm} />
  }

  // secondary chips — max 1 visible (availability only), no overflow chip
  const secondaryChip = vm.availabilityLabel ?? vm.fitOutLabel ?? null

  return (
    <Box sx={{
      borderRadius: 2,
      overflow: 'hidden',
      border: `1px solid ${DS_BORDER.default}`,
      bgcolor: '#ffffff',
      boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
      display: 'flex',
      flexDirection: 'column',
      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,
      },
    }}>

      {/* ── Hero zone ── */}
      <Box sx={{ position: 'relative' }}>
        <LocationPreview imageUrl={imageUrl} lat={lat} lng={lng} cityLabel={cityLabel} height={200} overlayTypeLabel={overlayTypeLabel} overlayLocationLabel={overlayLocationLabel} />

        {/* Score badge — bottom-left editorial */}
        <Box sx={{
          position: 'absolute', bottom: 10, left: 12,
          bgcolor: theme.gradient, borderRadius: '8px',
          px: 1.25, py: 0.375,
          border: `1px solid ${theme.border}`,
        }}>
          <Typography sx={{
            fontWeight: 700, fontSize: '1.625rem',
            color: '#ffffff', lineHeight: 1, letterSpacing: '-0.02em',
          }}>
            {vm.matchScore}%
          </Typography>
        </Box>

        {/* Location pill — Ginesta-style, top-left */}
        <Box sx={{
          position: 'absolute', top: 10, left: 10,
          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>

        {/* Top-right badge strip — result type + owner + heat */}
        <Box sx={{ position: 'absolute', top: 10, right: 10, display: 'flex', flexDirection: 'column', gap: 0.5, alignItems: 'flex-end' }}>
          <Chip label={rt.label} size="small" sx={{ bgcolor: rt.color, color: 'white', fontWeight: 600, fontSize: 10, height: 20 }} />
          {vm.resultType === 'VERIFIED_PORTFOLIO' && isPortfolioOwner && (
            <Chip
              icon={<Building2 size={9} color="#152642" />}
              label="Ihr Objekt"
              size="small"
              sx={{ bgcolor: 'rgba(21,38,66,0.85)', color: 'white', fontWeight: 700, fontSize: 9, height: 18, '& .MuiChip-icon': { ml: 0.5 } }}
            />
          )}
          <HeatBadge propertyId={vm.propertyId} size="sm" />
        </Box>
      </Box>

      {/* ── Card body ── */}
      <Box sx={{ p: 2.25, flex: 1, display: 'flex', flexDirection: 'column', gap: 0 }}>

        {/* Title */}
        <Typography variant="subtitle1" sx={{ fontWeight: 700, lineHeight: 1.3, color: DS_TEXT.primary }} noWrap>
          {vm.title}
        </Typography>
        {vm.propertySubtitle && (
          <Typography variant="caption" sx={{ display: 'block', mt: 0.125, color: DS_TEXT.secondary, fontWeight: 500 }} noWrap>
            {vm.propertySubtitle}
          </Typography>
        )}
        <Typography variant="caption" sx={{ color: DS_TEXT.muted, display: 'block', mt: 0.25 }}>
          {[vm.locationLabel, vm.availabilityLabel].filter(Boolean).join(' · ')}
        </Typography>

        {/* Unit details */}
        {vm.preMarketUnit && (
          <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.68rem', mt: 0.25 }}>
            {vm.preMarketUnit.areaSqm.toLocaleString('de-CH')} m²
            {vm.preMarketUnit.rentPricePerSqm
              ? ` · CHF ${Math.round(vm.preMarketUnit.rentPricePerSqm / 12).toLocaleString('de-CH')}/m²/Mt.`
              : ''}
          </Typography>
        )}

        {/* Confidence + one secondary chip max */}
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 1, alignItems: 'center' }}>
          <Chip label={`${confPct}% Konfidenz`} size="small"
            sx={{ bgcolor: confidenceHex(vm.confidenceScore), color: 'white', fontSize: 10, height: 20 }} />
          {secondaryChip && (
            <Chip label={secondaryChip} size="small" variant="outlined"
              sx={{ fontSize: 10, height: 20, borderColor: DS_BORDER.default, color: DS_TEXT.secondary }} />
          )}
        </Box>

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

        {vm.reasons.length > 0 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5, mt: 1 }}>
            {vm.reasons.slice(0, 2).map((r, i) => (
              <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.75 }}>
                <CheckCircle2 size={13} color="#1d6342" style={{ marginTop: 2, flexShrink: 0 }} />
                <Box>
                  <Typography sx={{ fontSize: '0.75rem', fontWeight: 600, color: DS_TEXT.primary, lineHeight: 1.3 }}>
                    {r.label}
                  </Typography>
                  <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.muted, lineHeight: 1.3 }}>
                    {r.explanation}
                  </Typography>
                </Box>
              </Box>
            ))}
          </Box>
        )}

        {/* Actions */}
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75, mt: 1.5, pt: 1.25, borderTop: `1px solid ${DS_BORDER.muted}` }}>
          <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>
          {vm.actions.map(a => (
            <Button
              key={a.id}
              size="small"
              variant={a.variant === 'primary' ? 'contained' : 'outlined'}
              onClick={a.onClick}
              disabled={a.disabled}
              sx={{ textTransform: 'none', fontSize: '0.7rem', py: 0.375, px: 1 }}
            >
              {a.label}
            </Button>
          ))}
        </Box>
      </Box>
    </Box>
  )
}
