import { Box, Divider, LinearProgress, Link, Paper, Typography } from '@mui/material'
import { CheckCircle2, ShieldCheck, X } from 'lucide-react'
import { ExternalLink } from 'lucide-react'
import type { Match } from '../../domain/match'
import type { FutureSignal } from '../../domain/futureSignal'
import { CREDIBILITY_LABELS, HARD_KEYS, factorLabel } from './scoreBreakdownConstants'
import { CriterionRow } from './CriterionRow'
import { criterionScoreColor, criterionScoreTextColor } from '../../lib/utils'
import { DS_COLORS, DS_TEXT, DS_SURFACE } from '../../lib/ds'
import { SCORE_STRONG, SCORE_MODERATE } from '../../lib/constants'

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

interface StandardBreakdownProps {
  match: Match
  taxCalculatorUrl?: string
}

function StandardBreakdown({ match, taxCalculatorUrl }: StandardBreakdownProps) {
  const sb = match.scoreBreakdown

  // Use allFactors when available (typed English keys); fall back to pos + neg
  const hasAllFactors = !!match.allFactors
  const allFactors = match.allFactors ?? [...match.positiveFactors, ...(match.negativeFactors ?? [])]

  const hardFactors = hasAllFactors
    ? allFactors.filter(f => HARD_KEYS.has(f.criterion))
    : allFactors  // static mock data: show flat, no grouping

  const softFactors = hasAllFactors
    ? allFactors.filter(f => !HARD_KEYS.has(f.criterion))
    : []

  const hardContrib = Math.round(sb.hardMatchScore * 0.60 * 10) / 10
  const softContrib = Math.round(sb.softFactorScore * 0.40 * 10) / 10
  const baseSum = Math.round((hardContrib + softContrib) * 10) / 10
  const maxHardWeight = Math.max(...hardFactors.map(f => f.weight), 0.001)
  const maxSoftWeight = Math.max(...softFactors.map(f => f.weight), 0.001)

  return (
    <>
      {/* Hard criteria */}
      <Typography variant="caption" sx={{ fontWeight: 700, color: 'primary.main', textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', mb: 1.25 }}>
        {hasAllFactors ? 'Hart-Kriterien' : 'Bewertungsfaktoren'}
      </Typography>

      {hardFactors.map((f, i) => <CriterionRow key={i} factor={f} maxWeight={maxHardWeight} />)}

      <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: DS_SURFACE.indigo.bg, px: 1.25, py: 0.75, borderRadius: 1, mt: 0.25, mb: hasAllFactors && softFactors.length > 0 ? 2 : 1.5 }}>
        <Typography variant="caption" sx={{ fontWeight: 600, color: 'primary.main' }}>
          Hart-Kriterien {sb.hardMatchScore}/100 × 60%
        </Typography>
        <Typography variant="caption" sx={{ fontWeight: 800, color: 'primary.main' }}>
          {hardContrib} Pkt
        </Typography>
      </Box>

      {/* Soft factors: full list when allFactors present, otherwise summary row */}
      {!hasAllFactors && (
        <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: DS_SURFACE.neutral.bg, px: 1.25, py: 0.75, borderRadius: 1, mb: 1.5 }}>
          <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.secondary }}>
            Soft-Faktoren {sb.softFactorScore}/100 × 40%
          </Typography>
          <Typography variant="caption" sx={{ fontWeight: 800, color: DS_TEXT.secondary }}>
            {softContrib} Pkt
          </Typography>
        </Box>
      )}

      {hasAllFactors && softFactors.length > 0 && (
        <>
          <Divider sx={{ mb: 2 }} />
          <Typography variant="caption" sx={{ fontWeight: 700, color: DS_TEXT.secondary, textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', mb: 1.25 }}>
            Soft-Faktoren
          </Typography>
          {softFactors.map((f, i) => <CriterionRow key={i} factor={f} maxWeight={maxSoftWeight} />)}
          <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: DS_SURFACE.neutral.bg, px: 1.25, py: 0.75, borderRadius: 1, mt: 0.25, mb: 1.5 }}>
            <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.secondary }}>
              Soft-Score {sb.softFactorScore}/100 × 40%
            </Typography>
            <Typography variant="caption" sx={{ fontWeight: 800, color: DS_TEXT.secondary }}>
              {softContrib} Pkt
            </Typography>
          </Box>
        </>
      )}

      {/* Tax link */}
      {taxCalculatorUrl && (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.5, p: 1.25, bgcolor: DS_SURFACE.info.bg, borderRadius: 1, border: `1px solid ${DS_SURFACE.info.border}` }}>
          <ExternalLink size={13} color={DS_TEXT.info} style={{ flexShrink: 0 }} />
          <Box>
            <Typography variant="caption" sx={{ color: DS_TEXT.info, fontWeight: 600, display: 'block', lineHeight: 1.2 }}>
              Steuerlast in Bewertung eingeflossen
            </Typography>
            <Link
              href={taxCalculatorUrl}
              target="_blank"
              rel="noopener noreferrer"
              underline="hover"
              sx={{ fontSize: '0.72rem', color: DS_TEXT.info }}
            >
              Steuerrechner Gemeinde öffnen →
            </Link>
          </Box>
        </Box>
      )}

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

      {/* Formula row — always visible */}
      <Box sx={{ bgcolor: DS_SURFACE.neutral.bg, px: 1.25, py: 0.75, borderRadius: 1, mb: 1.25 }}>
        <Typography variant="caption" sx={{ color: DS_TEXT.muted, display: 'block', mb: 0.4, fontWeight: 500 }}>
          Berechnung
        </Typography>
        <Typography variant="caption" sx={{ fontFamily: 'monospace', color: DS_TEXT.primary, display: 'block', lineHeight: 1.6 }}>
          Hart {sb.hardMatchScore} × 60% + Soft {sb.softFactorScore} × 40%
          {' = '}{hardContrib} + {softContrib} = {baseSum}
        </Typography>
      </Box>

      {/* Total */}
      <Box sx={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        bgcolor: baseSum >= SCORE_STRONG ? DS_SURFACE.success.bg : baseSum >= SCORE_MODERATE ? DS_SURFACE.warning.bg : DS_SURFACE.error.bg,
        p: 1.5, borderRadius: 1,
      }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>Gesamt-Score</Typography>
        <Typography
          variant="h4"
          sx={{ fontWeight: 800, color: criterionScoreTextColor(Math.round(baseSum)) }}
        >
          {baseSum}/100
        </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

  const signalDeduction = signal && !isVerifiedContract
    ? Math.round((1 - signal.probability) * sb.hardMatchScore * 0.18)
    : 0

  // Use allFactors or fall back to pos + neg
  const displayFactors = match.allFactors
    ? match.allFactors
    : [...match.positiveFactors, ...(match.negativeFactors ?? [])]

  return (
    <>
      {/* Schritt 1 — Kriterien-Match */}
      <Box sx={{ mb: 2 }}>
        <Typography variant="caption" sx={{ fontWeight: 700, color: DS_COLORS.futureCard.controlled.accent, 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>

        {displayFactors.map((f, i) => {
          const isPositive = f.score >= 70
          return (
            <Box key={i} sx={{ mb: 1.25 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.6, mb: 0.4 }}>
                {isPositive
                  ? <CheckCircle2 size={12} color={DS_TEXT.success} style={{ flexShrink: 0 }} />
                  : <X size={12} color={DS_TEXT.error} style={{ flexShrink: 0 }} />
                }
                <Box sx={{ flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.primary }}>{factorLabel(f.criterion)}</Typography>
                  <Typography variant="caption" sx={{ fontWeight: 700, color: criterionScoreTextColor(f.score), ml: 1 }}>{f.score}/100</Typography>
                </Box>
              </Box>
              <LinearProgress
                variant="determinate"
                value={f.score}
                color={criterionScoreColor(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>
          )
        })}

        <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: DS_SURFACE.neutral.bg, px: 1.25, py: 0.75, borderRadius: 1, mt: 0.5 }}>
          <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.secondary }}>Basis-Score</Typography>
          <Typography variant="caption" sx={{ fontWeight: 800, color: DS_TEXT.primary }}>{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: DS_COLORS.futureCard.controlled.accent, 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={DS_TEXT.success} style={{ flexShrink: 0 }} />
              <Typography variant="caption" sx={{ color: DS_TEXT.success, 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={DS_TEXT.success} style={{ flexShrink: 0 }} />
              <Typography variant="caption" sx={{ color: DS_TEXT.success, lineHeight: 1.3 }}>
                Verwaltung hat Freigabe erteilt
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: DS_SURFACE.success.bg, px: 1.25, py: 0.75, borderRadius: 1, border: `1px solid ${DS_SURFACE.success.border}` }}>
              <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.success }}>Signal-Abschlag</Typography>
              <Typography variant="caption" sx={{ fontWeight: 800, color: DS_TEXT.success }}>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: DS_TEXT.error }}>–{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: DS_TEXT.warning }}>–{Math.round(signalDeduction * 0.3)} Pkt.</Typography>
              </Box>
            )}
            <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: DS_SURFACE.orange.bg, px: 1.25, py: 0.75, borderRadius: 1, border: `1px solid ${DS_SURFACE.orange.border}` }}>
              <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.warning }}>Signal-Abschlag</Typography>
              <Typography variant="caption" sx={{ fontWeight: 800, color: DS_TEXT.warning }}>–{signalDeduction} Punkte</Typography>
            </Box>
          </>
        )}
      </Box>

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

      {/* Gesamt */}
      <Box sx={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', bgcolor: DS_SURFACE.neutral.bg, p: 1.5, borderRadius: 1 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>Gesamt-Score</Typography>
        <Typography
          variant="h4"
          sx={{ fontWeight: 800, color: criterionScoreTextColor(sb.totalScore) }}
        >
          {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) {
  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>
    )
  }

  return (
    <Paper sx={{ p: 2.5, mb: 2 }}>
      <Typography variant="h6" sx={{ fontWeight: 700, mb: 2 }}>Bewertungsherleitung</Typography>
      <StandardBreakdown match={match} taxCalculatorUrl={taxCalculatorUrl} />
    </Paper>
  )
}
