import { Box, Chip, Divider, Drawer, IconButton, Typography } from '@mui/material'
import { X, AlertCircle, AlertTriangle, Zap } from 'lucide-react'
import type { ConnectorRun } from '../../domain/dataSource'
import { CONNECTOR_RUN_STATUS_LABELS, CONNECTOR_RUN_STATUS_COLORS } from '../../domain/dataSource'

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString('de-CH', {
    day: '2-digit', month: '2-digit', year: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
  })
}

interface ConnectorRunDetailDrawerProps {
  run: ConnectorRun | null
  onClose: () => void
}

export function ConnectorRunDetailDrawer({ run, onClose }: ConnectorRunDetailDrawerProps) {
  return (
    <Drawer
      anchor="right"
      open={run !== null}
      onClose={onClose}
      slotProps={{ paper: { sx: { width: 400 } } }}
    >
      {run && (
        <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
          {/* Header */}
          <Box sx={{ px: 3, py: 2, borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 1 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 600, flex: 1 }}>
              Import-Run Details
            </Typography>
            <IconButton size="small" onClick={onClose}>
              <X size={16} />
            </IconButton>
          </Box>

          <Box sx={{ flex: 1, overflowY: 'auto', p: 3 }}>
            {/* Status */}
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
              <Chip
                size="small"
                label={CONNECTOR_RUN_STATUS_LABELS[run.status]}
                sx={{
                  bgcolor: CONNECTOR_RUN_STATUS_COLORS[run.status].bg,
                  color: CONNECTOR_RUN_STATUS_COLORS[run.status].fg,
                  border: 'none',
                  fontWeight: 600,
                }}
              />
              <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                {run.id}
              </Typography>
            </Box>

            {/* Timestamps */}
            <Box sx={{ mb: 2 }}>
              <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>
                Gestartet: <strong>{formatDate(run.startedAt)}</strong>
              </Typography>
              {run.finishedAt && (
                <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>
                  Beendet: <strong>{formatDate(run.finishedAt)}</strong>
                </Typography>
              )}
            </Box>

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

            {/* Stats grid */}
            <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1.5, mb: 2 }}>
              {[
                { label: 'Erkannt', value: run.itemsDetected, color: '#1e293b' },
                { label: 'Normalisiert', value: run.itemsNormalized, color: '#15803d' },
                { label: 'Abgelehnt', value: run.itemsRejected, color: run.itemsRejected > 0 ? '#dc2626' : '#64748b' },
                { label: 'Signale erstellt', value: run.signalsCreated, color: '#7c3aed' },
              ].map(({ label, value, color }) => (
                <Box key={label} sx={{ p: 1.5, bgcolor: '#f8fafc', borderRadius: 1, border: '1px solid #e2e8f0' }}>
                  <Typography sx={{ fontSize: '1.25rem', fontWeight: 700, color, lineHeight: 1 }}>
                    {value}
                  </Typography>
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>{label}</Typography>
                </Box>
              ))}
            </Box>

            {/* Summary */}
            <Divider sx={{ mb: 2 }} />
            <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 0.75 }}>
              Zusammenfassung
            </Typography>
            <Typography variant="body2" sx={{ color: '#1e293b', lineHeight: 1.5, mb: 2 }}>
              {run.runSummary}
            </Typography>

            {/* Signals note */}
            {run.signalsCreated > 0 && (
              <Box sx={{ p: 1.5, bgcolor: 'rgba(124,58,237,0.06)', border: '1px solid rgba(124,58,237,0.2)', borderRadius: 1, display: 'flex', gap: 1, mb: 2 }}>
                <Zap size={14} color="#7c3aed" style={{ flexShrink: 0, marginTop: 2 }} />
                <Typography variant="body2" sx={{ color: '#7c3aed', fontSize: '0.78rem' }}>
                  {run.signalsCreated} Marktsignal{run.signalsCreated !== 1 ? 'e' : ''} aus diesem Run verfügbar in Market Intelligence.
                </Typography>
              </Box>
            )}

            {/* Errors */}
            {run.errors.length > 0 && (
              <>
                <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 0.75 }}>
                  Fehler
                </Typography>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75, mb: 2 }}>
                  {run.errors.map((err, i) => (
                    <Box key={i} sx={{ display: 'flex', gap: 0.75, p: 1, bgcolor: 'rgba(239,68,68,0.06)', borderRadius: 1 }}>
                      <AlertCircle size={13} color="#dc2626" style={{ flexShrink: 0, marginTop: 1 }} />
                      <Typography variant="caption" sx={{ color: '#dc2626', lineHeight: 1.4 }}>{err}</Typography>
                    </Box>
                  ))}
                </Box>
              </>
            )}

            {/* Warnings */}
            {run.warnings.length > 0 && (
              <>
                <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 0.75 }}>
                  Warnungen
                </Typography>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}>
                  {run.warnings.map((w, i) => (
                    <Box key={i} sx={{ display: 'flex', gap: 0.75, p: 1, bgcolor: 'rgba(234,179,8,0.06)', borderRadius: 1 }}>
                      <AlertTriangle size={13} color="#a16207" style={{ flexShrink: 0, marginTop: 1 }} />
                      <Typography variant="caption" sx={{ color: '#a16207', lineHeight: 1.4 }}>{w}</Typography>
                    </Box>
                  ))}
                </Box>
              </>
            )}
          </Box>
        </Box>
      )}
    </Drawer>
  )
}
