import { Box, Divider, LinearProgress, Link, Paper, Typography } from '@mui/material'
import { CheckCircle2, ExternalLink, ShieldCheck, X } from 'lucide-react'
import type { Match } from '../../domain/match'
import type { FutureSignal } from '../../domain/futureSignal'

// ── Shared helpers ─────────────────────────────────────────────────────────────

function scoreColor(v: number): 'success' | 'warning' | 'error' {
  return v >= 70 ? 'success' : v >= 50 ? 'warning' : 'error'
}

const CREDIBILITY_LABELS: Record<string, string> = {
  HIGH:   'Hohe Quellenqualität',
  MEDIUM: 'Mittlere Quellenqualität',
  LOW:    'Niedrige Quellenqualität',
}

// ── Standard breakdown (VERIFIED_PORTFOLIO / EXTERNAL / MAISON) ──────────────

interface BreakdownRowProps {
  label: string
  value: number
  max: number
  description: string
  color?: 'success' | 'warning' | 'error' | 'primary'
  modifier?: boolean
}

function BreakdownRow({ label, value, max, description, color = 'primary', modifier }: BreakdownRowProps) {
  const pct = Math.round((Math.abs(value) / max) * 100)
  const isNegative = modifier && value < 0
  const isPositive = modifier && value > 0

  return (
    <Box sx={{ mb: 2 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
        <Typography variant="body2" sx={{ fontWeight: 500 }}>{label}</Typography>
        <Typography
          variant="body2"
          sx={{ fontWeight: 700, color: isNegative ? '#c0392b' : isPositive ? '#1a7a4a' : 'text.primary' }}
        >
          {modifier && value > 0 ? '+' : ''}{modifier ? value : `${value}/${max}`}
        </Typography>
      </Box>
      {!modifier && (
        <LinearProgress
          variant="determinate"
          value={Math.min(pct, 100)}
          sx={{ height: 8, borderRadius: 4, mb: 0.5 }}
          color={color}
        />
      )}
      <Typography variant="caption" color="text.secondary">{description}</Typography>
    </Box>
  )
}

// ── Signal score derivation (FUTURE_AVAILABILITY) ─────────────────────────────

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

function SignalScoreDerivation({ match, signal }: SignalScoreDerivationProps) {
  const sb = match.scoreBreakdown
  const isVerifiedContract = signal?.isVerified && signal?.source?.type === 'LEASE_CONTRACT'
  const probPct = signal ? Math.round(signal.probability * 100) : null
  const credLabel = signal ? (CREDIBILITY_LABELS[signal.source.credibility] ?? signal.source.credibility) : null

  // Approximate signal deduction for display purposes
  const signalDeduction = signal && !isVerifiedContract
    ? Math.round((1 - signal.probability) * sb.hardMatchScore * 0.18)
    : 0

  return (
    <>
      {/* Schritt 1 — Kriterien-Match */}
      <Box sx={{ mb: 2 }}>
        <Typography variant="caption" sx={{ fontWeight: 700, color: '#6d28d9', textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', mb: 0.75 }}>
          Schritt 1 — Kriterien-Match
        </Typography>
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1.25, lineHeight: 1.4 }}>
          Wie gut passt die Fläche, wenn das Signal eintrifft?
        </Typography>

        {match.positiveFactors.map((f, i) => (
          <Box key={i} sx={{ mb: 1.25 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.6, mb: 0.4 }}>
              <CheckCircle2 size={12} color="#1a7a4a" style={{ flexShrink: 0 }} />
              <Box sx={{ flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <Typography variant="caption" sx={{ fontWeight: 600, color: '#1e293b' }}>{f.criterion}</Typography>
                <Typography variant="caption" sx={{ fontWeight: 700, color: '#1a7a4a', ml: 1 }}>{f.score}/100</Typography>
              </Box>
            </Box>
            <LinearProgress
              variant="determinate"
              value={f.score}
              color={scoreColor(f.score)}
              sx={{ height: 5, borderRadius: 3, mb: 0.35, ml: 2.25 }}
            />
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', ml: 2.25, lineHeight: 1.3 }}>
              {f.explanation}
            </Typography>
          </Box>
        ))}

        {(match.negativeFactors ?? []).map((f, i) => (
          <Box key={i} sx={{ mb: 1.25 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.6, mb: 0.4 }}>
              <X size={12} color="#c0392b" style={{ flexShrink: 0 }} />
              <Box sx={{ flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <Typography variant="caption" sx={{ fontWeight: 600, color: '#1e293b' }}>{f.criterion}</Typography>
                <Typography variant="caption" sx={{ fontWeight: 700, color: '#c0392b', ml: 1 }}>{f.score}/100</Typography>
              </Box>
            </Box>
            <LinearProgress
              variant="determinate"
              value={f.score}
              color="error"
              sx={{ height: 5, borderRadius: 3, mb: 0.35, ml: 2.25 }}
            />
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', ml: 2.25, lineHeight: 1.3 }}>
              {f.explanation}
            </Typography>
          </Box>
        ))}

        <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: '#f8fafc', px: 1.25, py: 0.75, borderRadius: 1, mt: 0.5 }}>
          <Typography variant="caption" sx={{ fontWeight: 600, color: '#475569' }}>Basis-Score</Typography>
          <Typography variant="caption" sx={{ fontWeight: 800, color: '#1e293b' }}>{sb.hardMatchScore}/100</Typography>
        </Box>
      </Box>

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

      {/* Schritt 2 — Verlässlichkeit */}
      <Box sx={{ mb: 2 }}>
        <Typography variant="caption" sx={{ fontWeight: 700, color: '#6d28d9', textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', mb: 0.75 }}>
          Schritt 2 — Verlässlichkeit des Signals
        </Typography>

        {isVerifiedContract ? (
          <>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 0.75 }}>
              <ShieldCheck size={13} color="#1a7a4a" style={{ flexShrink: 0 }} />
              <Typography variant="caption" sx={{ color: '#1a7a4a', lineHeight: 1.3 }}>
                Vertragsende aus ERP verifiziert — keine Schätzung
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 1 }}>
              <ShieldCheck size={13} color="#1a7a4a" style={{ flexShrink: 0 }} />
              <Typography variant="caption" sx={{ color: '#1a7a4a', lineHeight: 1.3 }}>
                Verwaltung hat Freigabe erteilt
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: '#f0fdf4', px: 1.25, py: 0.75, borderRadius: 1, border: '1px solid #bbf7d0' }}>
              <Typography variant="caption" sx={{ fontWeight: 600, color: '#1a7a4a' }}>Signal-Abschlag</Typography>
              <Typography variant="caption" sx={{ fontWeight: 800, color: '#1a7a4a' }}>keiner</Typography>
            </Box>
          </>
        ) : (
          <>
            {probPct !== null && (
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', mb: 0.5 }}>
                <Typography variant="caption" color="text.secondary">Eintretenswahrscheinlichkeit: {probPct}%</Typography>
                <Typography variant="caption" sx={{ fontWeight: 600, color: '#c0392b' }}>–{Math.round(signalDeduction * 0.7)} Pkt.</Typography>
              </Box>
            )}
            {credLabel && (
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', mb: 1 }}>
                <Typography variant="caption" color="text.secondary">Quellenqualität: {credLabel}</Typography>
                <Typography variant="caption" sx={{ fontWeight: 600, color: '#d97706' }}>–{Math.round(signalDeduction * 0.3)} Pkt.</Typography>
              </Box>
            )}
            <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: '#fff7ed', px: 1.25, py: 0.75, borderRadius: 1, border: '1px solid #fed7aa' }}>
              <Typography variant="caption" sx={{ fontWeight: 600, color: '#d97706' }}>Signal-Abschlag</Typography>
              <Typography variant="caption" sx={{ fontWeight: 800, color: '#d97706' }}>–{signalDeduction} Punkte</Typography>
            </Box>
          </>
        )}
      </Box>

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

      {/* Gesamt */}
      <Box sx={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', bgcolor: '#f8fafc', p: 1.5, borderRadius: 1 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>Gesamt-Score</Typography>
        <Typography
          variant="h4"
          sx={{
            fontWeight: 800,
            color: sb.totalScore >= 78 ? '#1a7a4a' : sb.totalScore >= 52 ? '#d97706' : '#c0392b',
          }}
        >
          {sb.totalScore}/100
        </Typography>
      </Box>
    </>
  )
}

// ── Public component ───────────────────────────────────────────────────────────

interface Props {
  match: Match
  taxCalculatorUrl?: string
  isFuture?: boolean
  signal?: FutureSignal | null
}

export function ScoreBreakdownPanel({ match, taxCalculatorUrl, isFuture, signal }: Props) {
  const sb = match.scoreBreakdown

  if (isFuture) {
    return (
      <Paper sx={{ p: 2.5, mb: 2 }}>
        <Typography variant="h6" sx={{ fontWeight: 700, mb: 2 }}>Bewertungsherleitung</Typography>
        <SignalScoreDerivation match={match} signal={signal ?? null} />
      </Paper>
    )
  }

  const hardColor = scoreColor(sb.hardMatchScore)
  const softColor = scoreColor(sb.softFactorScore)

  return (
    <Paper sx={{ p: 2.5, mb: 2 }}>
      <Typography variant="h6" sx={{ fontWeight: 700, mb: 2 }}>Score Breakdown</Typography>

      <BreakdownRow
        label="Hard-Kriterien (60%)"
        value={sb.hardMatchScore}
        max={100}
        description="Fläche, Standort, Budget, Timing"
        color={hardColor}
      />
      <BreakdownRow
        label="Soft Factors (40%)"
        value={sb.softFactorScore}
        max={100}
        description="Prestige, Erreichbarkeit, ESG, Steuerlast"
        color={softColor}
      />

      {taxCalculatorUrl && (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.5, p: 1.25, bgcolor: '#f0f9ff', borderRadius: 1, border: '1px solid #bae6fd' }}>
          <ExternalLink size={13} color="#0369a1" style={{ flexShrink: 0 }} />
          <Box>
            <Typography variant="caption" sx={{ color: '#0369a1', fontWeight: 600, display: 'block', lineHeight: 1.2 }}>
              KI hat Steuerlast bewertet
            </Typography>
            <Link
              href={taxCalculatorUrl}
              target="_blank"
              rel="noopener noreferrer"
              underline="hover"
              sx={{ fontSize: '0.72rem', color: '#0369a1' }}
            >
              Steuerrechner Gemeinde öffnen →
            </Link>
          </Box>
        </Box>
      )}

      <Divider sx={{ my: 1.5 }} />

      <BreakdownRow
        label="Datenqualitäts-Modifier"
        value={sb.dataQualityModifier}
        max={15}
        description="Basierend auf Vollständigkeit und Aktualität der Objektdaten"
        modifier
      />
      <BreakdownRow
        label="Konfidenz-Modifier"
        value={sb.confidenceModifier}
        max={15}
        description="Basierend auf Quelltyp (Verified/Extern/Signal)"
        modifier
      />

      <Divider sx={{ my: 1.5 }} />

      <Box sx={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', bgcolor: '#f8fafc', p: 1.5, borderRadius: 1 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>Gesamt-Score</Typography>
        <Typography
          variant="h4"
          sx={{
            fontWeight: 800,
            color: sb.totalScore >= 78 ? '#1a7a4a' : sb.totalScore >= 52 ? '#d97706' : '#c0392b',
          }}
        >
          {sb.totalScore}/100
        </Typography>
      </Box>
    </Paper>
  )
}
