import { Box, Divider, IconButton, LinearProgress, Typography } from '@mui/material'
import { X } from 'lucide-react'
import { ReviewEntityTypeBadge } from './ReviewEntityTypeBadge'
import { ReviewPriorityBadge } from './ReviewPriorityBadge'
import { ReviewStatusBadge } from './ReviewStatusBadge'
import { ReviewNotesPanel } from './ReviewNotesPanel'
import { ReviewActionToolbar } from './ReviewActionToolbar'
import type { ReviewTask, ReviewTaskStatus } from '../../domain/review'
import type { UserRole } from '../../domain/enums'

interface ReviewDetailPanelProps {
  task: ReviewTask
  userRole: UserRole
  onClose: () => void
  onAction: (status: ReviewTaskStatus) => void
  onAddNote: (content: string) => void
  isSubmitting?: boolean
}

const ENTITY_TYPE_LABELS: Record<string, string> = {
  FUTURE_SIGNAL:        'Zukunftssignal',
  MATCH_EXPLANATION:    'Match-Begründung',
  LOW_CONFIDENCE_MATCH: 'Niedr. Konfidenz-Match',
  CONTACT_RELEASE:      'Kontaktfreigabe',
  AI_OUTPUT:            'AI-Output',
  PROPERTY_DATA_ISSUE:  'Datenfehler',
}

const RISK_LABELS: Record<string, string> = {
  LOW: 'Niedrig', MEDIUM: 'Mittel', HIGH: 'Hoch', CRITICAL: 'Kritisch',
}

const RISK_COLORS: Record<string, string> = {
  LOW: '#1a7a4a', MEDIUM: '#d97706', HIGH: '#ea580c', CRITICAL: '#c0392b',
}

function MetaRow({ label, value }: { label: string; value: string | undefined }) {
  if (!value) return null
  return (
    <Box sx={{ display: 'flex', gap: 1, mb: 0.5 }}>
      <Typography variant="caption" color="text.secondary" sx={{ minWidth: 110, flexShrink: 0 }}>
        {label}
      </Typography>
      <Typography variant="caption" sx={{ fontWeight: 500, color: '#334155' }}>
        {value}
      </Typography>
    </Box>
  )
}

export function ReviewDetailPanel({
  task,
  userRole,
  onClose,
  onAction,
  onAddNote,
  isSubmitting,
}: ReviewDetailPanelProps) {
  const isActive = task.status === 'PENDING' || task.status === 'IN_REVIEW' || task.status === 'ESCALATED'
  const canAddNote = isActive || task.status === 'NEEDS_MORE_DATA'

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      {/* Header */}
      <Box sx={{ px: 2, py: 1.5, borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mb: 0.5 }}>
              <ReviewEntityTypeBadge entityType={task.entityType} />
              <ReviewPriorityBadge priority={task.priority} />
              <ReviewStatusBadge status={task.status} />
            </Box>
            <Typography variant="subtitle2" sx={{ fontWeight: 700, fontSize: '0.875rem', lineHeight: 1.3 }}>
              {task.title}
            </Typography>
          </Box>
          <IconButton size="small" onClick={onClose} sx={{ flexShrink: 0, mt: -0.25 }}>
            <X size={16} />
          </IconButton>
        </Box>
      </Box>

      {/* Scrollable body */}
      <Box sx={{ flex: 1, overflowY: 'auto', px: 2, py: 1.5 }}>
        {/* Description */}
        {task.description && (
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5, fontSize: '0.8125rem', lineHeight: 1.5 }}>
            {task.description}
          </Typography>
        )}

        {/* Metadata */}
        <Box sx={{ mb: 1.5 }}>
          <MetaRow label="Typ" value={ENTITY_TYPE_LABELS[task.entityType] ?? task.entityType} />
          <MetaRow label="Erstellt von" value={task.createdBy} />
          <MetaRow label="Zugewiesen" value={task.assignedTo} />
          <MetaRow label="Fällig" value={task.dueDate ? new Date(task.dueDate).toLocaleDateString('de-CH') : undefined} />
          {task.relatedOrganizationId && (
            <MetaRow label="Organisation" value={task.relatedOrganizationId} />
          )}
          {task.promptVersion && (
            <MetaRow label="Prompt-Version" value={task.promptVersion} />
          )}
        </Box>

        {/* Confidence / Risk context */}
        {(task.confidenceScore !== undefined || task.riskLevel) && (
          <>
            <Divider sx={{ mb: 1.5 }} />
            {task.confidenceScore !== undefined && (
              <Box sx={{ mb: 1.25 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.4 }}>
                  <Typography variant="caption" color="text.secondary">Konfidenz</Typography>
                  <Typography variant="caption" sx={{ fontWeight: 700 }}>
                    {Math.round(task.confidenceScore * 100)}%
                  </Typography>
                </Box>
                <LinearProgress
                  variant="determinate"
                  value={task.confidenceScore * 100}
                  sx={{
                    height: 4,
                    borderRadius: 2,
                    bgcolor: '#e2e8f0',
                    '& .MuiLinearProgress-bar': {
                      bgcolor: task.confidenceScore >= 0.7 ? '#1a7a4a' : task.confidenceScore >= 0.5 ? '#d97706' : '#c0392b',
                    },
                  }}
                />
              </Box>
            )}
            {task.riskLevel && (
              <Box sx={{ display: 'flex', gap: 1, mb: 0.5 }}>
                <Typography variant="caption" color="text.secondary" sx={{ minWidth: 110 }}>Risikostufe</Typography>
                <Typography
                  variant="caption"
                  sx={{ fontWeight: 700, color: RISK_COLORS[task.riskLevel] ?? '#64748b' }}
                >
                  {RISK_LABELS[task.riskLevel] ?? task.riskLevel}
                </Typography>
              </Box>
            )}
            {task.matchScore !== undefined && (
              <Box sx={{ display: 'flex', gap: 1, mb: 0.5 }}>
                <Typography variant="caption" color="text.secondary" sx={{ minWidth: 110 }}>Match-Score</Typography>
                <Typography variant="caption" sx={{ fontWeight: 700 }}>{task.matchScore}%</Typography>
              </Box>
            )}
          </>
        )}

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

        {/* Actions */}
        <Box sx={{ mb: 1.5 }}>
          <ReviewActionToolbar
            task={task}
            userRole={userRole}
            onAction={onAction}
            isSubmitting={isSubmitting}
          />
        </Box>

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

        {/* Notes */}
        <ReviewNotesPanel
          notes={task.reviewNotes}
          canAddNote={canAddNote}
          onAddNote={onAddNote}
          isSubmitting={isSubmitting}
        />
      </Box>
    </Box>
  )
}
