import { Box, Chip, Divider, LinearProgress, Paper, Typography } from '@mui/material'
import {
  AlertTriangle,
  Calendar,
  CheckCircle2,
  Clock,
  ShieldCheck,
  Sparkles,
  TrendingUp,
  Zap,
} from 'lucide-react'
import type { Match } from '../../domain/match'
import type { FutureSignal } from '../../domain/futureSignal'
import { SIGNAL_TYPE_LABELS, SIGNAL_ACTION, SOURCE_META } from './futureAvailabilityConstants'
import { CREDIBILITY_META, SENSITIVITY_META, RISK_META, ageLabel } from './futureAvailabilityContextUtils'
import { SignalSourcesSection } from './SignalSourcesSection'
import { DS_TEXT, DS_BG, DS_SURFACE, DS_PRE_MARKET, DS_MARKET_SIGNAL, DS_BORDER } from '../../lib/ds'

interface Props {
  match: Match
  signal: FutureSignal | null
}

export function FutureAvailabilityContextPanel({ match: _match, signal }: Props) {
  if (!signal) return null

  const sourceMeta = SOURCE_META[signal.source.type] ?? null
  const credMeta   = CREDIBILITY_META[signal.source.credibility] ?? null
  const sensitiveMeta = SENSITIVITY_META[signal.sensitivityLevel] ?? SENSITIVITY_META.PUBLIC
  const riskMeta   = signal.riskLevel ? (RISK_META[signal.riskLevel] ?? null) : null
  const probPct    = Math.round(signal.probability * 100)
  const isVerifiedContract = signal.isVerified && signal.source.type === 'LEASE_CONTRACT'
  const action     = signal.signalType ? (SIGNAL_ACTION[signal.signalType] ?? null) : null
  const allSourceUrls = [
    ...(signal.source.url ? [signal.source.url] : []),
    ...(signal.evidence?.sourceUrls ?? []),
  ]

  const probBarColor = probPct >= 70 ? DS_TEXT.success : probPct >= 50 ? DS_TEXT.warning : DS_TEXT.error

  return (
    <Paper sx={{ p: 2.5, mb: 2 }}>

      {/* ── Header ── */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.75, flexWrap: 'wrap' }}>
        <Zap size={16} color={DS_PRE_MARKET.accent} />
        <Typography variant="h6" sx={{ fontWeight: 700 }}>Future Availability Signal</Typography>
        {signal.isVerified && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.4, bgcolor: DS_SURFACE.success.bg, border: `1px solid ${DS_SURFACE.success.border}`, borderRadius: 1, px: 0.75, py: 0.2 }}>
            <ShieldCheck size={11} color={DS_TEXT.success} />
            <Typography sx={{ fontSize: '0.68rem', color: DS_TEXT.success, fontWeight: 700 }}>Verifiziert</Typography>
          </Box>
        )}
        <Box sx={{ ml: 'auto', display: 'flex', alignItems: 'center', gap: 0.5, color: DS_TEXT.disabled }}>
          <Clock size={12} />
          <Typography variant="caption" color="text.secondary">{ageLabel(signal.createdAt)}</Typography>
        </Box>
      </Box>

      {signal.title && (
        <Typography sx={{ fontSize: '0.95rem', fontWeight: 600, color: DS_TEXT.primary, mb: 2, lineHeight: 1.4 }}>
          {signal.title}
        </Typography>
      )}

      {/* ── 1. KI-Zusammenfassung ── */}
      {signal.aiSummary && (
        <Box sx={{ mb: 2.5 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 0.875 }}>
            <Sparkles size={14} color={DS_PRE_MARKET.accent} />
            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DS_TEXT.signalDark, fontSize: '0.8125rem' }}>KI-Zusammenfassung</Typography>
          </Box>
          <Box sx={{ bgcolor: DS_SURFACE.purple.bg, border: `1px solid ${DS_SURFACE.purple.border}`, borderRadius: 1.5, p: 1.75 }}>
            <Typography variant="body2" sx={{ color: DS_TEXT.primary, lineHeight: 1.7 }}>
              {signal.aiSummary}
            </Typography>
          </Box>
        </Box>
      )}

      {/* ── 2. Strategische Einschätzung ── */}
      {signal.strategicInterpretation && (
        <Box sx={{ mb: 2.5 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 0.875 }}>
            <TrendingUp size={14} color={DS_TEXT.info} />
            <Typography variant="subtitle2" sx={{ fontWeight: 700, fontSize: '0.8125rem' }}>Strategische Einschätzung</Typography>
          </Box>
          <Box sx={{ bgcolor: DS_SURFACE.info.bg, border: `1px solid ${DS_SURFACE.info.border}`, borderRadius: 1.5, p: 1.75 }}>
            <Typography variant="body2" sx={{ color: DS_TEXT.infoDark, lineHeight: 1.7 }}>
              {signal.strategicInterpretation}
            </Typography>
          </Box>
        </Box>
      )}

      {/* ── 3. Handlungsempfehlung ── */}
      {action && (
        <Box sx={{
          display: 'flex', alignItems: 'flex-start', gap: 1,
          bgcolor: action.urgency === 'high' ? DS_SURFACE.orange.bg : DS_BG.page,
          border: `1px solid ${action.urgency === 'high' ? DS_SURFACE.orange.border : DS_BORDER.default}`,
          borderRadius: 1.5, px: 1.5, py: 1.25, mb: 2.5,
        }}>
          <Zap size={14} color={action.urgency === 'high' ? DS_TEXT.error : DS_TEXT.muted} style={{ flexShrink: 0, marginTop: 2 }} />
          <Box>
            <Typography sx={{ fontSize: '0.72rem', fontWeight: 700, color: action.urgency === 'high' ? DS_TEXT.warningDark : DS_TEXT.secondary, mb: 0.25 }}>Empfohlene Aktion</Typography>
            <Typography sx={{ fontSize: '0.82rem', color: action.urgency === 'high' ? DS_TEXT.error : DS_TEXT.primary, lineHeight: 1.5 }}>{action.label}</Typography>
          </Box>
        </Box>
      )}

      <Divider sx={{ mb: 2 }} />

      {/* ── 4. Signal-Kenndaten ── */}
      <Box sx={{ mb: 2.5 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 1.25, fontSize: '0.8125rem' }}>Signal-Kenndaten</Typography>

        <Box sx={{ mb: 1.5 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.4 }}>
            <Typography variant="caption" color="text.secondary">Eintretenswahrscheinlichkeit</Typography>
            <Typography variant="caption" sx={{ fontWeight: 700, color: probBarColor }}>{probPct}%</Typography>
          </Box>
          <LinearProgress
            variant="determinate"
            value={probPct}
            sx={{
              height: 6, borderRadius: 3, bgcolor: DS_BG.subtle,
              '& .MuiLinearProgress-bar': { bgcolor: probBarColor, borderRadius: 3 },
            }}
          />
        </Box>

        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1.5 }}>
          {signal.signalType && (
            <Box>
              <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.25 }}>Signaltyp</Typography>
              <Chip label={SIGNAL_TYPE_LABELS[signal.signalType] ?? signal.signalType} size="small" sx={{ bgcolor: DS_PRE_MARKET.badgeBg, color: DS_PRE_MARKET.accentHover, fontWeight: 600 }} />
            </Box>
          )}
          <Box>
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.25 }}>Zeithorizont</Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <Calendar size={13} color={DS_TEXT.muted} />
              <Typography variant="body2" sx={{ fontWeight: 700 }}>~{signal.timeHorizonMonths} Monate</Typography>
            </Box>
          </Box>
          {signal.areaSqmEstimate && (
            <Box>
              <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.25 }}>Flächenschätzung</Typography>
              <Typography variant="body2" sx={{ fontWeight: 700 }}>~{signal.areaSqmEstimate.toLocaleString('de-CH')} m²</Typography>
            </Box>
          )}
          {riskMeta && (
            <Box>
              <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.25 }}>Risikoniveau</Typography>
              <Typography variant="body2" sx={{ fontWeight: 700, color: riskMeta.color }}>{riskMeta.label}</Typography>
            </Box>
          )}
        </Box>
      </Box>

      <Divider sx={{ mb: 2 }} />

      {/* ── 5. Erkannte Marktindikatoren ── */}
      {signal.marketIndicators && signal.marketIndicators.length > 0 && (
        <Box sx={{ mb: 2.5 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 1, fontSize: '0.8125rem' }}>Erkannte Marktindikatoren</Typography>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}>
            {signal.marketIndicators.map((indicator, i) => (
              <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.875 }}>
                <Box sx={{ width: 6, height: 6, borderRadius: '50%', bgcolor: DS_MARKET_SIGNAL.accent, mt: '6px', flexShrink: 0 }} />
                <Typography variant="body2" sx={{ color: DS_TEXT.primary, lineHeight: 1.55 }}>{indicator}</Typography>
              </Box>
            ))}
          </Box>
        </Box>
      )}

      {/* ── 6. Transparenz ── */}
      {((signal.confirmedFacts && signal.confirmedFacts.length > 0) ||
        (signal.unconfirmedFacts && signal.unconfirmedFacts.length > 0)) && (
        <Box sx={{ mb: 2.5 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 1, fontSize: '0.8125rem' }}>Transparenz — Was ist gesichert?</Typography>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.625 }}>
            {(signal.confirmedFacts ?? []).map((fact, i) => (
              <Box key={`c-${i}`} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.75 }}>
                <CheckCircle2 size={14} color={DS_TEXT.success} style={{ flexShrink: 0, marginTop: 1 }} />
                <Typography variant="body2" sx={{ color: DS_TEXT.success, fontWeight: 500, lineHeight: 1.45 }}>{fact}</Typography>
              </Box>
            ))}
            {(signal.unconfirmedFacts ?? []).map((fact, i) => (
              <Box key={`u-${i}`} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.75 }}>
                <AlertTriangle size={14} color={DS_TEXT.warning} style={{ flexShrink: 0, marginTop: 1 }} />
                <Typography variant="body2" sx={{ color: DS_TEXT.warningDark, lineHeight: 1.45 }}>{fact}</Typography>
              </Box>
            ))}
          </Box>
        </Box>
      )}

      <Divider sx={{ mb: 2 }} />

      {/* ── 7. Quellen & Belege ── */}
      <SignalSourcesSection
        sourceMeta={sourceMeta}
        credMeta={credMeta}
        isVerifiedContract={isVerifiedContract}
        allSourceUrls={allSourceUrls}
        signal={signal}
      />

      {/* ── Footer ── */}
      <Divider sx={{ mb: 1.5 }} />

      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.25, flexWrap: 'wrap' }}>
        <Typography variant="caption" color="text.secondary">Vertraulichkeit:</Typography>
        <Chip label={sensitiveMeta.label} size="small" color={sensitiveMeta.color} variant="outlined" />
        {signal.verifiedBy && (
          <>
            <Typography variant="caption" color="text.secondary">Verifiziert von:</Typography>
            <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.success }}>{signal.verifiedBy}</Typography>
          </>
        )}
      </Box>

      <Typography variant="caption" color="text.secondary" sx={{ display: 'block', lineHeight: 1.55, bgcolor: DS_BG.page, borderRadius: 1, px: 1.25, py: 1, fontStyle: 'italic' }}>
        {signal.disclaimer}
      </Typography>
    </Paper>
  )
}
