import { Alert, Box, Button, Chip, Divider, LinearProgress, Tooltip, Typography } from '@mui/material'
import {
  BarChart2,
  Briefcase,
  Building2,
  CheckCircle2,
  ExternalLink,
  FileCheck,
  FileText,
  Newspaper,
  ShieldCheck,
  TrendingUp,
  User,
  Zap,
} from 'lucide-react'
import { LocationPreview } from '../shared/LocationPreview'
import { getScoreTier, SCORE_THEME } from '../shared/scoreTheme'
import type { MatchCardViewModel } from './MatchCardViewModel'

// ── Constants ─────────────────────────────────────────────────────────────────

const RESULT_TYPE_META: Record<string, { label: string; color: string }> = {
  VERIFIED_PORTFOLIO:  { label: 'Verified Portfolio', color: '#1e3a5f' },
  EXTERNAL_MARKET:     { label: 'Direktinserat',      color: '#d97706' },
  MAISON_WORK:         { label: 'Maison Work',        color: '#0369a1' },
  FUTURE_AVAILABILITY: { label: 'Schattenmarkt',      color: '#7c3aed' },
}

const SOURCE_META: Record<string, { label: string; icon: React.ReactNode }> = {
  JOB_POSTING:        { label: 'Stelleninserate',    icon: <Briefcase size={11} /> },
  PRESS:              { label: 'Pressebericht',       icon: <Newspaper size={11} /> },
  CONSTRUCTION_PERMIT:{ label: 'Baubewilligung',      icon: <FileCheck size={11} /> },
  COMPANY_REPORT:     { label: 'Geschäftsbericht',    icon: <FileText size={11} /> },
  MARKET_DATA:        { label: 'Marktdaten',          icon: <BarChart2 size={11} /> },
  MANUAL:             { label: 'Analyst',             icon: <User size={11} /> },
  LEASE_CONTRACT:     { label: 'Vertrag verifiziert', icon: <ShieldCheck size={11} /> },
}

const SIGNAL_TYPE_LABELS: Record<string, string> = {
  EXPANSION:           'Expansion',
  POSSIBLE_MOVE_OUT:   'Möglicher Auszug',
  CONSTRUCTION_PROJECT:'Bauprojekt',
  RESTRUCTURING:       'Restrukturierung',
  PROJECT_DEVELOPMENT: 'Projektentwicklung',
  SPACE_CONSOLIDATION: 'Flächenkonsolidierung',
  LEASE_EXPIRY:        'Vertragsende',
}

// Human-readable explanation of WHY a signal type is relevant to a space search
const SIGNAL_RELEVANCE_BRIDGE: Record<string, string> = {
  EXPANSION:           'Neuer Flächenbedarf entsteht — Fläche wird gesucht',
  POSSIBLE_MOVE_OUT:   'Fläche könnte frei werden — frühzeitig beobachten',
  CONSTRUCTION_PROJECT:'Neubau geplant — zukünftige Verfügbarkeit möglich',
  RESTRUCTURING:       'Flächenveränderung durch Restrukturierung möglich',
  PROJECT_DEVELOPMENT: 'Projektentwicklung — neue Flächen in Planung',
  SPACE_CONSOLIDATION: 'Konsolidierung — Teilflächen könnten verfügbar werden',
}

const CREDIBILITY_META: Record<string, { label: string; color: string }> = {
  HIGH:   { label: 'Hohe Quellenqualität', color: '#1a7a4a' },
  MEDIUM: { label: 'Mittlere Quellenqualität', color: '#d97706' },
  LOW:    { label: 'Niedrige Quellenqualität', color: '#c0392b' },
}

// ── Schattenmarkt hero zone ───────────────────────────────────────────────────

function SignalHero({ vm }: { vm: MatchCardViewModel }) {
  const tier = getScoreTier(vm.matchScore)
  const theme = SCORE_THEME[tier]
  const signalLabel = vm.signalType ? (SIGNAL_TYPE_LABELS[vm.signalType] ?? vm.signalType) : 'Signal'
  const relevanceBridge = vm.signalType ? (SIGNAL_RELEVANCE_BRIDGE[vm.signalType] ?? null) : null
  const initials = (vm.title ?? '?')
    .split(/\s+/)
    .slice(0, 2)
    .map(w => w[0])
    .join('')
    .toUpperCase()

  return (
    <Box sx={{ position: 'relative' }}>
      {/* Gradient hero background */}
      <Box
        sx={{
          height: 140,
          background: 'linear-gradient(135deg, #1a0a3a 0%, #3b0a6e 50%, #6d28d9 100%)',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          gap: 0.5,
          position: 'relative',
          overflow: 'hidden',
          px: 7,
        }}
      >
        {/* Subtle pattern overlay */}
        <Box sx={{
          position: 'absolute', inset: 0, opacity: 0.08,
          backgroundImage: 'radial-gradient(circle at 20% 50%, white 1px, transparent 1px), radial-gradient(circle at 80% 20%, white 1px, transparent 1px)',
          backgroundSize: '40px 40px',
        }} />

        {/* Company initials */}
        <Box sx={{
          width: 40, height: 40, borderRadius: '50%',
          bgcolor: 'rgba(255,255,255,0.15)',
          border: '1.5px solid rgba(255,255,255,0.3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 1, flexShrink: 0,
        }}>
          <Typography sx={{ color: 'white', fontWeight: 800, fontSize: '0.9rem', letterSpacing: 1 }}>
            {initials}
          </Typography>
        </Box>

        {/* Signal type label */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, zIndex: 1 }}>
          <Zap size={10} color="#c4b5fd" />
          <Typography sx={{ color: '#c4b5fd', fontSize: '0.63rem', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.8 }}>
            {signalLabel}
          </Typography>
        </Box>

        {/* Relevance bridge — why this appears in results */}
        {relevanceBridge && (
          <Typography sx={{ color: 'rgba(255,255,255,0.85)', fontSize: '0.67rem', textAlign: 'center', lineHeight: 1.3, zIndex: 1 }}>
            {relevanceBridge}
          </Typography>
        )}

        {/* Verified badge */}
        {vm.signalIsVerified && (
          <Box sx={{ position: 'absolute', bottom: 8, right: 8, display: 'flex', alignItems: 'center', gap: 0.4, bgcolor: 'rgba(26,122,74,0.9)', borderRadius: 1, px: 0.75, py: 0.25 }}>
            <ShieldCheck size={10} color="white" />
            <Typography sx={{ color: 'white', fontSize: '0.6rem', fontWeight: 700 }}>Verifiziert</Typography>
          </Box>
        )}
      </Box>

      {/* Score badge — overlaid top-left */}
      <Box sx={{
        position: 'absolute', top: 10, left: 10,
        background: theme.gradient, borderRadius: '10px',
        px: 1.5, py: 0.5,
        boxShadow: `0 4px 16px ${theme.glow}`,
        border: `1px solid ${theme.border}`,
        minWidth: 52, textAlign: 'center',
      }}>
        <Typography sx={{ fontWeight: 900, fontSize: '1.5rem', color: theme.text, lineHeight: 1 }}>
          {vm.matchScore}%
        </Typography>
        {tier !== 'bronze' && (
          <Typography sx={{ fontSize: '0.575rem', color: theme.text, opacity: 0.8, textTransform: 'uppercase', letterSpacing: 0.8, lineHeight: 1.2 }}>
            {theme.label}
          </Typography>
        )}
      </Box>

      {/* Schattenmarkt chip — top-right */}
      <Box sx={{ position: 'absolute', top: 10, right: 10 }}>
        <Chip label="Schattenmarkt" size="small" sx={{ bgcolor: '#7c3aed', color: 'white', fontWeight: 700, fontSize: 10, height: 20 }} />
      </Box>
    </Box>
  )
}

// ── Signal metadata strip ─────────────────────────────────────────────────────

function SignalMetaStrip({ vm }: { vm: MatchCardViewModel }) {
  const sourceMeta = vm.signalSourceType ? SOURCE_META[vm.signalSourceType] : null
  const credMeta = vm.signalSourceCredibility ? CREDIBILITY_META[vm.signalSourceCredibility] : null
  const probPct = vm.signalProbability ? Math.round(vm.signalProbability * 100) : null

  return (
    <Box sx={{ px: 1.75, pt: 1.5, pb: 0, display: 'flex', flexDirection: 'column', gap: 1 }}>
      {/* Source + credibility row */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexWrap: 'wrap' }}>
        {sourceMeta && (
          vm.signalSourceUrl ? (
            <Box
              component="a"
              href={vm.signalSourceUrl}
              target="_blank"
              rel="noopener noreferrer"
              sx={{ display: 'flex', alignItems: 'center', gap: 0.4, bgcolor: '#ede9fe', color: '#6d28d9', borderRadius: 1, px: 0.75, py: 0.25, textDecoration: 'none', '&:hover': { bgcolor: '#ddd6fe' } }}
            >
              {sourceMeta.icon}
              <Typography sx={{ fontSize: '0.68rem', fontWeight: 600 }}>{sourceMeta.label}</Typography>
              <ExternalLink size={9} style={{ opacity: 0.7 }} />
            </Box>
          ) : (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.4, bgcolor: '#ede9fe', color: '#6d28d9', borderRadius: 1, px: 0.75, py: 0.25 }}>
              {sourceMeta.icon}
              <Typography sx={{ fontSize: '0.68rem', fontWeight: 600 }}>{sourceMeta.label}</Typography>
            </Box>
          )
        )}
        {credMeta && (
          <Tooltip title={credMeta.label} arrow>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.3, bgcolor: '#f8fafc', border: `1px solid ${credMeta.color}30`, borderRadius: 1, px: 0.6, py: 0.2, cursor: 'default' }}>
              <Box sx={{ width: 6, height: 6, borderRadius: '50%', bgcolor: credMeta.color }} />
              <Typography sx={{ fontSize: '0.63rem', color: credMeta.color, fontWeight: 600 }}>
                {vm.signalSourceCredibility === 'HIGH' ? 'Hoch' : vm.signalSourceCredibility === 'MEDIUM' ? 'Mittel' : 'Niedrig'}
              </Typography>
            </Box>
          </Tooltip>
        )}
      </Box>

      {/* Probability bar */}
      {probPct !== null && (
        <Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.3 }}>
            <Typography sx={{ fontSize: '0.63rem', color: '#64748b', fontWeight: 600 }}>Eintretenswahrscheinlichkeit</Typography>
            <Typography sx={{ fontSize: '0.63rem', fontWeight: 700, color: probPct >= 70 ? '#1a7a4a' : probPct >= 50 ? '#d97706' : '#c0392b' }}>
              {probPct}%
            </Typography>
          </Box>
          <LinearProgress
            variant="determinate"
            value={probPct}
            sx={{
              height: 4, borderRadius: 2,
              bgcolor: '#e2e8f0',
              '& .MuiLinearProgress-bar': {
                bgcolor: probPct >= 70 ? '#1a7a4a' : probPct >= 50 ? '#d97706' : '#c0392b',
                borderRadius: 2,
              },
            }}
          />
        </Box>
      )}

      {/* Market indicator */}
      {vm.signalMarketIndicator && (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, bgcolor: '#f0fdf4', borderRadius: 1, px: 0.75, py: 0.4 }}>
          <TrendingUp size={11} color="#1a7a4a" style={{ flexShrink: 0 }} />
          <Typography sx={{ fontSize: '0.68rem', color: '#1a7a4a', fontWeight: 500 }}>
            {vm.signalMarketIndicator}
          </Typography>
        </Box>
      )}
    </Box>
  )
}

// ── Main component ────────────────────────────────────────────────────────────

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

export function IntelligenceMatchCard({ vm, imageUrl, lat, lng, cityLabel }: Props) {
  const tier = getScoreTier(vm.matchScore)
  const theme = SCORE_THEME[tier]
  const rt = RESULT_TYPE_META[vm.resultType] ?? { label: vm.resultType, color: '#64748b' }
  const isFuture = vm.resultType === 'FUTURE_AVAILABILITY'

  return (
    <Box sx={{
      borderRadius: 2,
      overflow: 'hidden',
      boxShadow: isFuture
        ? '0 2px 16px rgba(109,40,217,0.15), 0 0 0 2px #7c3aed'
        : `0 2px 16px rgba(0,0,0,0.07), 0 0 0 1px ${theme.cardBorder}`,
      background: theme.cardBg,
      display: 'flex',
      flexDirection: 'column',
      transition: 'box-shadow 0.15s, transform 0.1s',
      '&:hover': {
        boxShadow: isFuture
          ? '0 6px 28px rgba(109,40,217,0.2), 0 0 0 2px #7c3aed'
          : `0 6px 28px rgba(0,0,0,0.12), 0 0 0 1px ${theme.cardBorder}`,
        transform: 'translateY(-1px)',
      },
    }}>

      {/* ── Hero zone ── */}
      {isFuture ? (
        <SignalHero vm={vm} />
      ) : (
        <Box sx={{ position: 'relative' }}>
          <LocationPreview imageUrl={imageUrl} lat={lat} lng={lng} cityLabel={cityLabel} height={175} />
          <Box sx={{
            position: 'absolute', top: 10, left: 10,
            background: theme.gradient, borderRadius: '10px',
            px: 1.5, py: 0.5,
            boxShadow: `0 4px 16px ${theme.glow}`,
            border: `1px solid ${theme.border}`,
            minWidth: 52, textAlign: 'center',
          }}>
            <Typography sx={{ fontWeight: 900, fontSize: '1.5rem', color: theme.text, lineHeight: 1 }}>
              {vm.matchScore}%
            </Typography>
            {tier !== 'bronze' && (
              <Typography sx={{ fontSize: '0.575rem', color: theme.text, opacity: 0.8, textTransform: 'uppercase', letterSpacing: 0.8, lineHeight: 1.2 }}>
                {theme.label}
              </Typography>
            )}
          </Box>
          <Box sx={{ position: 'absolute', top: 10, right: 44, 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' && (
              <Chip
                icon={<Building2 size={9} color="#1e3a5f" />}
                label="Ihr Objekt"
                size="small"
                sx={{ bgcolor: 'rgba(30,58,95,0.85)', color: 'white', fontWeight: 700, fontSize: 9, height: 18, '& .MuiChip-icon': { ml: 0.5 } }}
              />
            )}
          </Box>
        </Box>
      )}

      {/* ── Signal metadata (Schattenmarkt only) ── */}
      {isFuture && <SignalMetaStrip vm={vm} />}

      {/* ── Card body ── */}
      <Box sx={{ p: isFuture ? 1.75 : 2, pt: isFuture ? 1 : 2, flex: 1, display: 'flex', flexDirection: 'column', gap: 0 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700, lineHeight: 1.3 }} noWrap>
          {vm.title}
        </Typography>
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.25 }}>
          {[vm.locationLabel, vm.availabilityLabel].filter(Boolean).join(' · ')}
        </Typography>

        {/* AI Signal Summary (Schattenmarkt) */}
        {isFuture && vm.aiSignalSummary && (
          <>
            <Divider sx={{ my: 1 }} />
            <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.75, bgcolor: '#faf5ff', borderRadius: 1, p: 1 }}>
              <Zap size={12} color="#7c3aed" style={{ flexShrink: 0, marginTop: 2 }} />
              <Typography variant="body2" sx={{
                fontSize: '0.72rem', color: '#4c1d95', lineHeight: 1.5,
                overflow: 'hidden', display: '-webkit-box',
                WebkitLineClamp: 4, WebkitBoxOrient: 'vertical',
              }}>
                {vm.aiSignalSummary}
              </Typography>
            </Box>
          </>
        )}

        {/* Regular explainability summary (non-future) */}
        {!isFuture && vm.explainabilitySummary && (
          <>
            <Divider sx={{ my: 1.25 }} />
            <Typography variant="body2" sx={{
              fontWeight: 500, color: '#1e293b', lineHeight: 1.5, flex: 1,
              overflow: 'hidden', display: '-webkit-box',
              WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
            }}>
              {vm.explainabilitySummary}
            </Typography>
          </>
        )}

        {vm.reasons.length > 0 && (
          <>
            <Divider sx={{ my: 1.25 }} />
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.625 }}>
              {vm.reasons.slice(0, 3).map((r, i) => (
                <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.75 }}>
                  <CheckCircle2 size={13} color="#1a7a4a" style={{ marginTop: 2, flexShrink: 0 }} />
                  <Box>
                    <Typography sx={{ fontSize: '0.75rem', fontWeight: 600, color: '#1e293b', lineHeight: 1.3 }}>
                      {r.label}
                    </Typography>
                    <Typography sx={{ fontSize: '0.72rem', color: '#64748b', lineHeight: 1.3 }}>
                      {r.explanation}
                    </Typography>
                  </Box>
                </Box>
              ))}
            </Box>
          </>
        )}

        {/* Actions */}
        <Box sx={{ display: 'flex', gap: 0.75, mt: 1.5, pt: 1.25, borderTop: '1px solid rgba(0,0,0,0.06)' }}>
          {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: isFuture ? '#7c3aed' : '#1e3a5f',
                  '&:hover': { bgcolor: isFuture ? '#6d28d9' : '#162d4a' },
                }),
              }}
            >
              {a.label}
            </Button>
          ))}
        </Box>
      </Box>

      {/* Disclaimer */}
      {vm.disclaimer && (
        <Alert severity="warning" sx={{ borderRadius: 0, py: 0.25, '& .MuiAlert-message': { fontSize: '0.7rem' } }}>
          {vm.disclaimer}
        </Alert>
      )}
    </Box>
  )
}
