import { useState } from 'react'
import { Alert, Box, Chip, CircularProgress, Collapse, Typography } from '@mui/material'
import { ChevronDown, ChevronUp, Trophy, TrendingDown, ShieldCheck, AlertTriangle, Info, ArrowRight, CheckCircle2, XCircle, Star } from 'lucide-react'
import type { ComparisonSummary } from '../../services/aiService'
import { DS_TEXT, DS_BG, DS_BORDER, DS_SURFACE } from '../../lib/ds'

interface Props {
  summary?: ComparisonSummary
  isLoading: boolean
}

export function AICompareSummary({ summary, isLoading }: Props) {
  const [open, setOpen] = useState(true)

  return (
    <Box sx={{ mb: 2, border: `1px solid ${DS_BORDER.default}`, borderRadius: 1, overflow: 'hidden' }}>
      <Box
        onClick={() => setOpen(v => !v)}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 2,
          py: 1.25,
          bgcolor: DS_SURFACE.neutral.bg,
          cursor: 'pointer',
          '&:hover': { bgcolor: DS_BG.subtle },
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>AI Vergleichs-Zusammenfassung</Typography>
          <Chip label="Beta" size="small" sx={{ fontSize: 10, bgcolor: DS_SURFACE.purple.bg, color: DS_TEXT.signal }} />
        </Box>
        {open ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
      </Box>

      <Collapse in={open}>
        <Box sx={{ p: 2 }}>
          {isLoading && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 1 }}>
              <CircularProgress size={16} />
              <Typography variant="body2" color="text.secondary">Analyse wird erstellt…</Typography>
            </Box>
          )}

          {!isLoading && summary && (
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
              {/* Overall assessment */}
              <Box sx={{ bgcolor: DS_SURFACE.info.bg, border: `1px solid ${DS_SURFACE.info.border}`, borderRadius: 1, p: 1.5 }}>
                <Typography variant="body2" sx={{ color: DS_TEXT.infoDark, lineHeight: 1.5 }}>{summary.overallAssessment}</Typography>
              </Box>

              {/* Strongest option */}
              <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
                <Trophy size={16} color={DS_TEXT.success} style={{ flexShrink: 0, marginTop: 2 }} />
                <Box>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block' }}>Stärkstes Match</Typography>
                  <Typography variant="body2" sx={{ fontWeight: 600 }}>{summary.strongestOption.label}</Typography>
                  <Typography variant="caption" color="text.secondary">{summary.strongestOption.reason}</Typography>
                </Box>
              </Box>

              {/* Best value */}
              {summary.bestValue && (
                <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
                  <TrendingDown size={16} color={DS_TEXT.brand} style={{ flexShrink: 0, marginTop: 2 }} />
                  <Box>
                    <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block' }}>Bestes Preis-Leistungs-Verhältnis</Typography>
                    <Typography variant="body2" sx={{ fontWeight: 600 }}>{summary.bestValue.label}</Typography>
                    <Typography variant="caption" color="text.secondary">{summary.bestValue.reason}</Typography>
                  </Box>
                </Box>
              )}

              {/* Highest confidence */}
              <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
                <ShieldCheck size={16} color="#0891b2" style={{ flexShrink: 0, marginTop: 2 }} />
                <Box>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block' }}>Höchste Datenkonfidenz</Typography>
                  <Typography variant="body2" sx={{ fontWeight: 600 }}>
                    {summary.highestConfidence.label}
                    <Typography component="span" variant="caption" color="text.secondary" sx={{ ml: 0.5 }}>
                      ({Math.round(summary.highestConfidence.confidenceLevel * 100)}%)
                    </Typography>
                  </Typography>
                </Box>
              </Box>

              {/* Tradeoffs */}
              {summary.biggestTradeoffs.length > 0 && (
                <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
                  <AlertTriangle size={16} color={DS_TEXT.warning} style={{ flexShrink: 0, marginTop: 2 }} />
                  <Box>
                    <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block' }}>Wichtigste Abwägungen</Typography>
                    {summary.biggestTradeoffs.map((t, i) => (
                      <Typography key={i} variant="caption" color="text.secondary" sx={{ display: 'block' }}>· {t}</Typography>
                    ))}
                  </Box>
                </Box>
              )}

              {/* Missing data */}
              {summary.missingDataWarnings.length > 0 && (
                <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
                  <Info size={16} color={DS_TEXT.error} style={{ flexShrink: 0, marginTop: 2 }} />
                  <Box>
                    <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block' }}>Fehlende Informationen</Typography>
                    {summary.missingDataWarnings.map((w, i) => (
                      <Typography key={i} variant="caption" color="error" sx={{ display: 'block' }}>· {w}</Typography>
                    ))}
                  </Box>
                </Box>
              )}

              {/* Per-property assessment */}
              {summary.perPropertyAssessment.length > 0 && (
                <Box>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block', mb: 0.75 }}>Objektbewertung</Typography>
                  <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}>
                    {summary.perPropertyAssessment.map(prop => (
                      <Box
                        key={prop.matchId}
                        sx={{
                          flex: '1 1 200px',
                          border: `1px solid ${DS_BORDER.default}`,
                          borderRadius: 1,
                          p: 1.25,
                          display: 'flex',
                          flexDirection: 'column',
                          gap: 0.75,
                        }}
                      >
                        <Typography variant="body2" sx={{ fontWeight: 700, color: DS_TEXT.brand }}>{prop.label}</Typography>

                        {/* Strengths */}
                        <Box>
                          {prop.strengths.map((s, i) => (
                            <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5, mb: 0.25 }}>
                              <CheckCircle2 size={12} color={DS_TEXT.success} style={{ flexShrink: 0, marginTop: 2 }} />
                              <Typography variant="caption" color="text.secondary" sx={{ lineHeight: 1.4 }}>{s}</Typography>
                            </Box>
                          ))}
                        </Box>

                        {/* Weaknesses */}
                        <Box>
                          {prop.weaknesses.map((w, i) => (
                            <Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5, mb: 0.25 }}>
                              <XCircle size={12} color={DS_TEXT.danger} style={{ flexShrink: 0, marginTop: 2 }} />
                              <Typography variant="caption" color="text.secondary" sx={{ lineHeight: 1.4 }}>{w}</Typography>
                            </Box>
                          ))}
                        </Box>

                        {/* Best for */}
                        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5 }}>
                          <Star size={12} color={DS_TEXT.warning} style={{ flexShrink: 0, marginTop: 2 }} />
                          <Typography variant="caption" sx={{ color: DS_TEXT.warningDark, lineHeight: 1.4 }}>
                            <strong>Am besten für:</strong> {prop.bestFor}
                          </Typography>
                        </Box>

                        {/* Key risk */}
                        {prop.keyRisk && (
                          <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5 }}>
                            <AlertTriangle size={12} color={DS_TEXT.warning} style={{ flexShrink: 0, marginTop: 2 }} />
                            <Typography variant="caption" color="text.secondary" sx={{ lineHeight: 1.4 }}>{prop.keyRisk}</Typography>
                          </Box>
                        )}
                      </Box>
                    ))}
                  </Box>
                </Box>
              )}

              {/* Recommendation */}
              <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start', pt: 0.5, borderTop: `1px solid ${DS_BORDER.muted}`, mt: 0.5 }}>
                <ArrowRight size={16} color={DS_TEXT.brand} style={{ flexShrink: 0, marginTop: 2 }} />
                <Box>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, display: 'block' }}>Empfehlung</Typography>
                  <Typography variant="body2">{summary.recommendation}</Typography>
                </Box>
              </Box>
            </Box>
          )}

          {!isLoading && !summary && (
            <Alert severity="info" sx={{ py: 0.5 }}>
              Mindestens 2 Ergebnisse auswählen, um die Zusammenfassung zu generieren.
            </Alert>
          )}

          <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.5, fontStyle: 'italic' }}>
            Diese Zusammenfassung basiert ausschliesslich auf den vorliegenden Daten und trifft keine endgültige Entscheidung.
          </Typography>
        </Box>
      </Collapse>
    </Box>
  )
}
