import { useState } from 'react'
import { Alert, Box, Button, Collapse, IconButton, Typography } from '@mui/material'
import { AlertTriangle, ChevronDown, ChevronUp, Target } from 'lucide-react'
import type { ReactNode } from 'react'

export interface DecisionMetric {
  label: string
  value: string | number
  severity?: 'neutral' | 'positive' | 'warning' | 'critical'
}

export interface DecisionAction {
  label: string
  primary?: boolean
  onClick: () => void
}

interface Props {
  /** The core question this screen answers */
  decision: string
  /** One-line explanation of why this decision matters */
  context?: string
  /** Key data points relevant to the decision */
  metrics?: DecisionMetric[]
  /** Missing data that could affect the decision */
  missing?: string[]
  /** Active risks the user should be aware of */
  risks?: string[]
  /** Available actions — first primary action is highlighted */
  actions?: DecisionAction[]
  /** Custom content after the standard rows */
  children?: ReactNode
}

const SEVERITY_DOT: Record<NonNullable<DecisionMetric['severity']>, string> = {
  neutral:  '#9a9a9a',
  positive: '#1d6342',
  warning:  '#a16207',
  critical: '#b91c1c',
}

const SEVERITY_TEXT: Record<NonNullable<DecisionMetric['severity']>, string> = {
  neutral:  '#5c5c5c',
  positive: '#1d6342',
  warning:  '#92400e',
  critical: '#991b1b',
}

export function DecisionContextPanel({
  decision,
  context,
  metrics = [],
  missing = [],
  risks = [],
  actions = [],
  children,
}: Props) {
  const [expanded, setExpanded] = useState(false)
  const hasDetails = missing.length > 0 || risks.length > 0 || !!children

  return (
    <Box
      sx={{
        bgcolor: '#f9f8f6',
        borderBottom: '1px solid #e8e7e4',
        px: 2.5,
        py: 1.25,
        flexShrink: 0,
      }}
    >
      {/* Main row */}
      <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2, flexWrap: 'wrap' }}>
        {/* Decision question */}
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, flex: 1, minWidth: 200 }}>
          <Target size={15} color="#152642" style={{ marginTop: 2, flexShrink: 0 }} />
          <Box>
            <Typography variant="body2" sx={{ fontWeight: 700, fontSize: '0.8125rem', color: '#141414', lineHeight: 1.3 }}>
              {decision}
            </Typography>
            {context && (
              <Typography variant="caption" sx={{ color: '#64748b', display: 'block', mt: 0.25 }}>
                {context}
              </Typography>
            )}
          </Box>
        </Box>

        {/* Metric chips */}
        {metrics.length > 0 && (
          <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', alignItems: 'center' }}>
            {metrics.map((m, i) => {
              const sev = m.severity ?? 'neutral'
              return (
                <Box key={i} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <Box sx={{ width: 6, height: 6, borderRadius: '50%', bgcolor: SEVERITY_DOT[sev], flexShrink: 0 }} />
                  <Typography sx={{ fontSize: '0.75rem', color: SEVERITY_TEXT[sev], fontWeight: sev !== 'neutral' ? 600 : 400, lineHeight: 1.2 }}>
                    {m.value} {m.label}
                  </Typography>
                </Box>
              )
            })}
          </Box>
        )}

        {/* Actions + expand toggle */}
        <Box sx={{ display: 'flex', gap: 0.75, alignItems: 'center', flexShrink: 0 }}>
          {actions.map((a, i) => (
            <Button
              key={i}
              size="small"
              variant={a.primary ? 'contained' : 'outlined'}
              onClick={a.onClick}
              sx={a.primary
                ? { bgcolor: '#152642', '&:hover': { bgcolor: '#0e1c30' }, textTransform: 'none', fontSize: '0.75rem', py: 0.375, px: 1.25 }
                : { textTransform: 'none', fontSize: '0.75rem', py: 0.375, px: 1.25 }
              }
            >
              {a.label}
            </Button>
          ))}
          {hasDetails && (
            <IconButton
              size="small"
              onClick={() => setExpanded(v => !v)}
              sx={{ color: '#64748b', width: 24, height: 24 }}
            >
              {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
            </IconButton>
          )}
        </Box>
      </Box>

      {/* Expandable details */}
      <Collapse in={expanded}>
        <Box sx={{ mt: 1.25, display: 'flex', flexDirection: 'column', gap: 0.75 }}>
          {risks.length > 0 && (
            <Alert severity="warning" icon={<AlertTriangle size={14} />} sx={{ py: 0.25, '& .MuiAlert-message': { fontSize: '0.75rem' } }}>
              <strong>Risiken:</strong>{' '}{risks.join(' · ')}
            </Alert>
          )}
          {missing.length > 0 && (
            <Alert severity="info" sx={{ py: 0.25, '& .MuiAlert-message': { fontSize: '0.75rem' } }}>
              <strong>Fehlende Daten:</strong>{' '}{missing.join(' · ')}
            </Alert>
          )}
          {children}
        </Box>
      </Collapse>
    </Box>
  )
}
