import { memo } from 'react'
import { Box, Button, Divider, Typography } from '@mui/material'
import { AlertCircle, CheckCircle2, ShieldCheck } from 'lucide-react'
import { useNavigate } from 'react-router'
import { getScoreTier, SCORE_THEME } from '../shared/scoreTheme'
import { floorLabel, SOURCE_META, ASSET_TYPE_LABELS, getOpportunityHeadline } from './futureAvailabilityCardHelpers'
import { SignalQualityDots } from './SignalQualityDots'
import { DS_COLORS, DS_TEXT, DS_SURFACE, DS_BORDER } from '../../lib/ds'
import type { MatchCardViewModel } from './MatchCardViewModel'

// ── Future Availability Card ──────────────────────────────────────────────────

export const FutureAvailabilityCard = memo(function FutureAvailabilityCard({ vm }: { vm: MatchCardViewModel }) {
  const isControlled = vm.signalIsControlled ?? false
  const navigate = useNavigate()

  const cardColors = isControlled ? DS_COLORS.futureCard.controlled : DS_COLORS.futureCard.signal
  const accentColor   = cardColors.accent
  const headerBg      = cardColors.headerBg
  const borderColor   = cardColors.border
  const badgeBg       = cardColors.badgeBg
  const badgeColor    = cardColors.badgeText

  const assetLabel = vm.assetType ? (ASSET_TYPE_LABELS[vm.assetType] ?? vm.assetType) : 'Fläche'
  const headline   = getOpportunityHeadline(vm.signalType, assetLabel)
  const sourceMeta = vm.signalSourceType ? (SOURCE_META[vm.signalSourceType] ?? null) : null
  const tier  = getScoreTier(vm.matchScore)
  const theme = SCORE_THEME[tier]

  return (
    <Box sx={{
      borderRadius: 2,
      overflow: 'hidden',
      border: `1px solid ${borderColor}`,
      background: 'white',
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 1px 8px rgba(0,0,0,0.06)',
      transition: 'box-shadow 0.15s, transform 0.1s',
      '&:hover': { boxShadow: '0 4px 20px rgba(0,0,0,0.10)', transform: 'translateY(-1px)' },
    }}>

      {/* ── Data header ─────────────────────────────────────────────────────── */}
      <Box sx={{ bgcolor: headerBg, px: 2, pt: 1.75, pb: 1.5, borderBottom: `1px solid ${borderColor}` }}>

        {/* Asset type · location + badge */}
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 0.5 }}>
          <Typography sx={{ fontSize: '0.63rem', fontWeight: 700, color: DS_TEXT.muted, textTransform: 'uppercase', letterSpacing: 0.8 }}>
            {assetLabel.toUpperCase()}  ·  {vm.locationLabel?.split(',')[0]?.toUpperCase() ?? ''}
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.4, bgcolor: badgeBg, color: badgeColor, px: 0.875, py: 0.25, borderRadius: 1, flexShrink: 0 }}>
            {isControlled && <ShieldCheck size={9} />}
            <Typography sx={{ fontSize: '0.6rem', fontWeight: 800, letterSpacing: 0.5 }}>
              {isControlled ? 'PRE-MARKET VERIFIED' : 'MARKET SIGNAL'}
            </Typography>
          </Box>
        </Box>

        {/* Opportunity headline */}
        <Typography variant="subtitle1" sx={{ fontWeight: 700, lineHeight: 1.3, color: DS_TEXT.primary, mb: 0.75 }}>
          {headline}
        </Typography>

        {/* Key facts */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap', mb: 0.875 }}>
          {vm.signalAreaSqmEstimate ? (
            <Typography sx={{ fontSize: '0.75rem', fontWeight: 700, color: DS_TEXT.primary }}>
              {isControlled ? '' : '~'}{vm.signalAreaSqmEstimate.toLocaleString('de-CH')} m²
            </Typography>
          ) : null}
          {vm.availabilityLabel && (
            <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.secondary }}>
              {vm.availabilityLabel}
            </Typography>
          )}
        </Box>

        {/* Source attribution */}
        {isControlled ? (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, bgcolor: DS_SURFACE.success.bg, border: `1px solid ${DS_SURFACE.success.border}`, borderRadius: 1, px: 0.875, py: 0.3, width: 'fit-content' }}>
            <ShieldCheck size={10} color={DS_TEXT.success} />
            <Typography sx={{ fontSize: '0.65rem', fontWeight: 700, color: DS_TEXT.success }}>Direkte Verwaltungsquelle</Typography>
          </Box>
        ) : sourceMeta ? (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, width: 'fit-content' }}>
            <Box sx={{ color: DS_TEXT.muted, display: 'flex' }}>{sourceMeta.icon}</Box>
            <Typography sx={{ fontSize: '0.65rem', color: DS_TEXT.muted, fontWeight: 500 }}>{sourceMeta.label}</Typography>
          </Box>
        ) : null}
      </Box>

      {/* ── Score + signal quality strip ────────────────────────────────────── */}
      <Box sx={{ px: 2, py: 1, display: 'flex', alignItems: 'center', gap: 1.5, borderBottom: `1px solid ${DS_BORDER.muted}`, bgcolor: 'white' }}>
        <Box sx={{
          background: theme.gradient, borderRadius: '8px',
          px: 1.25, py: 0.4, border: `1px solid ${theme.border}`,
          boxShadow: `0 2px 8px ${theme.glow}`,
        }}>
          <Typography sx={{ fontWeight: 900, fontSize: '1.25rem', color: theme.text, lineHeight: 1 }}>
            {vm.matchScore}%
          </Typography>
        </Box>
        <SignalQualityDots quality={vm.signalQuality} />
        {!isControlled && vm.signalProbability !== undefined && (
          <Box sx={{ ml: 'auto', bgcolor: DS_SURFACE.neutral.bg, border: `1px solid ${DS_BORDER.default}`, borderRadius: 1, px: 0.75, py: 0.2 }}>
            <Typography sx={{ fontSize: '0.63rem', color: DS_TEXT.muted, fontWeight: 600 }}>
              {Math.round(vm.signalProbability * 100)}% Signalw.
            </Typography>
          </Box>
        )}
      </Box>

      {/* ── Card body ───────────────────────────────────────────────────────── */}
      <Box sx={{ px: 2, pt: 1.5, pb: 1.5, flex: 1, display: 'flex', flexDirection: 'column' }}>

        {/* MARKET SIGNAL: probabilistic notice */}
        {!isControlled && (
          <Box sx={{
            display: 'flex', alignItems: 'flex-start', gap: 0.6, mb: 1.25,
            bgcolor: DS_SURFACE.warning.bg, border: `1px solid ${DS_SURFACE.warning.border}`, borderRadius: 1, px: 1, py: 0.625,
          }}>
            <AlertCircle size={11} color={DS_COLORS.heat.VERY_HOT.text} style={{ marginTop: 2, flexShrink: 0 }} />
            <Typography sx={{ fontSize: '0.67rem', color: DS_COLORS.heat.VERY_HOT.text, lineHeight: 1.45 }}>
              Probabilistischer Marktindikator — kein bestätigtes Objekt. Dient als strategischer Frühindikator.
            </Typography>
          </Box>
        )}

        {/* PRE-MARKET VERIFIED: confirmed facts */}
        {isControlled && (vm.signalConfirmedFacts?.length ?? 0) > 0 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.4, mb: 1.25 }}>
            {(vm.signalConfirmedFacts ?? []).slice(0, 3).map((fact, i) => (
              <Box key={i} sx={{ display: 'flex', alignItems: 'center', gap: 0.6 }}>
                <CheckCircle2 size={12} color={DS_TEXT.success} style={{ flexShrink: 0 }} />
                <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.success, fontWeight: 500 }}>{fact}</Typography>
              </Box>
            ))}
          </Box>
        )}

        {/* PRE-MARKET VERIFIED: specific unit info */}
        {isControlled && vm.preMarketUnit && (
          <Box sx={{ bgcolor: DS_SURFACE.success.bg, border: `1px solid ${DS_SURFACE.success.border}`, borderRadius: 1, px: 1.25, py: 0.875, mb: 1.25 }}>
            <Typography sx={{ fontSize: '0.63rem', fontWeight: 700, color: DS_TEXT.success, textTransform: 'uppercase', letterSpacing: 0.5, mb: 0.4 }}>
              Freigegebene Einheit
            </Typography>
            <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}>
              <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.primary, fontWeight: 600 }}>
                {floorLabel(vm.preMarketUnit.floorLevel)}{vm.preMarketUnit.unitLabel ? ` · ${vm.preMarketUnit.unitLabel}` : ''}
              </Typography>
              <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.secondary }}>
                {vm.preMarketUnit.areaSqm.toLocaleString('de-CH')} m²
              </Typography>
              {vm.preMarketUnit.schattenmarktRelease?.availableFrom && (
                <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.secondary }}>
                  ab {new Date(vm.preMarketUnit.schattenmarktRelease.availableFrom).toLocaleDateString('de-CH', { month: 'short', year: 'numeric' })}
                </Typography>
              )}
            </Box>
          </Box>
        )}

        {/* MARKET SIGNAL: market indicators */}
        {!isControlled && (vm.signalMarketIndicators?.length ?? 0) > 0 && (
          <Box sx={{ mb: 1.25 }}>
            <Typography sx={{ fontSize: '0.63rem', fontWeight: 700, color: DS_TEXT.muted, textTransform: 'uppercase', letterSpacing: 0.6, mb: 0.5 }}>
              Erkannte Marktindikatoren
            </Typography>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.35 }}>
              {(vm.signalMarketIndicators ?? []).slice(0, 3).map((ind, i) => (
                <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.6 }}>
                  <Box sx={{ width: 4, height: 4, borderRadius: '50%', bgcolor: DS_COLORS.futureCard.signal.indicator, mt: '5px', flexShrink: 0 }} />
                  <Typography sx={{ fontSize: '0.72rem', color: DS_TEXT.secondary, lineHeight: 1.3 }}>{ind}</Typography>
                </Box>
              ))}
            </Box>
          </Box>
        )}

        {/* Why relevant — match reasons */}
        {vm.reasons.length > 0 && (
          <>
            <Divider sx={{ mb: 1 }} />
            <Typography sx={{ fontSize: '0.63rem', fontWeight: 700, color: DS_TEXT.muted, textTransform: 'uppercase', letterSpacing: 0.6, mb: 0.6 }}>
              Warum relevant für Ihre Suche?
            </Typography>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5, mb: 1.25 }}>
              {vm.reasons.slice(0, 3).map((r, i) => (
                <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.6 }}>
                  <CheckCircle2 size={12} color={DS_TEXT.success} style={{ marginTop: 2, flexShrink: 0 }} />
                  <Box>
                    <Typography sx={{ fontSize: '0.72rem', fontWeight: 600, color: DS_TEXT.primary, lineHeight: 1.3 }}>{r.label}</Typography>
                    <Typography sx={{ fontSize: '0.69rem', color: DS_TEXT.muted, lineHeight: 1.3 }}>{r.explanation}</Typography>
                  </Box>
                </Box>
              ))}
            </Box>
          </>
        )}

        {/* Actions */}
        <Box sx={{ display: 'flex', gap: 0.75, mt: 'auto', pt: 1.25, borderTop: '1px solid rgba(0,0,0,0.06)', flexWrap: 'wrap' }}>
          {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.variant === 'primary' && {
                  bgcolor: accentColor,
                  '&:hover': { bgcolor: cardColors.accentHover },
                }),
              }}
            >
              {a.label}
            </Button>
          ))}
          {isControlled && vm.propertyId && (
            <Button
              size="small"
              variant="contained"
              onClick={() => navigate(`/demand/property/${vm.propertyId}${vm.unitId ? `?unit=${vm.unitId}` : ''}`)}
              sx={{
                textTransform: 'none', fontSize: '0.7rem', py: 0.375, px: 1,
                bgcolor: DS_COLORS.futureCard.controlled.accent,
                '&:hover': { bgcolor: DS_COLORS.futureCard.controlled.accentHover },
                ml: 'auto',
              }}
            >
              Zur Einheit →
            </Button>
          )}
        </Box>

        {/* Disclaimer footnote */}
        {vm.disclaimer && (
          <Typography variant="caption" color="text.disabled" sx={{ display: 'block', mt: 1, fontSize: '0.63rem', lineHeight: 1.4, borderTop: `1px solid ${DS_BORDER.muted}`, pt: 0.75 }}>
            {vm.disclaimer}
          </Typography>
        )}
      </Box>
    </Box>
  )
})
