import { useEffect, useRef, useState } from 'react'
import { Box, Button, CircularProgress, Dialog, LinearProgress, Typography } from '@mui/material'
import { CheckCircle, Download, FileText } from 'lucide-react'
import type { MarketReport } from '../../domain/marketReport'
import { DS_TEXT, DS_BG, DS_BORDER, DS_SURFACE } from '../../lib/ds'

const SECTION_COLORS: Record<string, string> = {
  development: '#1e3a5f',
  demand: '#1a7a4a',
  supply: '#b45309',
  negotiation: '#7c3aed',
}
const SECTION_LABELS: Record<string, string> = {
  development: 'Entwicklungsnews',
  demand: 'Nachfrage 5 km',
  supply: 'Angebot 5 km',
  negotiation: 'Verhandlungshinweise',
}

interface BerichtDialogProps {
  onClose: () => void
  report: MarketReport | null
  propertyId: string
}

export function BerichtDialog({ onClose, report, propertyId }: BerichtDialogProps) {
  const [ready, setReady] = useState(false)
  const [progress, setProgress] = useState(0)
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  useEffect(() => {
    let p = 0
    timerRef.current = setInterval(() => {
      p += Math.random() * 18 + 8
      if (p >= 100) {
        clearInterval(timerRef.current!)
        setProgress(100)
        setReady(true)
      } else {
        setProgress(Math.min(100, p))
      }
    }, 200)
    return () => { if (timerRef.current) clearInterval(timerRef.current) }
  }, [])

  function handleDownload() {
    const signals = report?.signals ?? []
    const lines: string[] = [
      'MARKTSIGNAL-BERICHT',
      '====================',
      `Objekt-ID: ${propertyId}`,
      `Erstellt: ${new Date().toLocaleString('de-CH')}`,
      '',
    ]
    for (const s of signals) {
      lines.push(`[${SECTION_LABELS[s.category] ?? s.category}]`)
      lines.push(s.title)
      lines.push(s.body)
      if (s.source) lines.push(`Quelle: ${s.source}`)
      lines.push('')
    }
    const blob = new Blob([lines.join('\n')], { type: 'application/pdf' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `Marktsignal-Bericht_${propertyId}.pdf`
    a.click()
    URL.revokeObjectURL(url)
    onClose()
  }

  const signals = report?.signals ?? []
  const categories = ['development', 'demand', 'supply', 'negotiation'] as const

  return (
    <Dialog
      open
      onClose={ready ? onClose : undefined}
      maxWidth="md"
      fullWidth
      slotProps={{ paper: { sx: { height: '88vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' } } }}
    >
      {/* Header */}
      <Box sx={{ px: 3, py: 1.5, borderBottom: `1px solid ${DS_BORDER.default}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
        <Box>
          <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.7rem', textTransform: 'uppercase', fontWeight: 600, letterSpacing: 0.5 }}>
            Bericht erstellen
          </Typography>
          <Typography variant="body1" sx={{ fontWeight: 700, color: '#0f172a', fontSize: '0.95rem' }}>
            Marktsignal-Bericht · {propertyId}
          </Typography>
        </Box>
        {ready && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <CheckCircle size={14} color={DS_TEXT.success} />
            <Typography variant="caption" sx={{ color: '#166534', fontWeight: 600 }}>Bereit</Typography>
          </Box>
        )}
      </Box>

      {/* Generating state */}
      {!ready && (
        <Box sx={{ px: 3, py: 1.5, borderBottom: `1px solid ${DS_BORDER.default}`, bgcolor: DS_SURFACE.neutral.bg, flexShrink: 0 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 1 }}>
            <CircularProgress size={16} />
            <Typography variant="caption" sx={{ color: '#374151' }}>
              PDF-Bericht wird generiert…
            </Typography>
            <Typography variant="caption" sx={{ color: DS_TEXT.disabled, ml: 'auto' }}>{Math.round(progress)}%</Typography>
          </Box>
          <LinearProgress
            variant="determinate"
            value={progress}
            sx={{ height: 4, borderRadius: 2, bgcolor: DS_BORDER.default, '& .MuiLinearProgress-bar': { bgcolor: DS_TEXT.brand } }}
          />
        </Box>
      )}

      {/* PDF Preview */}
      <Box sx={{ flex: 1, overflow: 'auto', bgcolor: DS_BG.subtle, p: 3 }}>
        <Box
          sx={{
            bgcolor: 'white',
            borderRadius: 1.5,
            border: `1px solid ${DS_BORDER.strong}`,
            boxShadow: '0 4px 16px rgba(15,23,42,0.08)',
            p: 4,
            fontFamily: '"Georgia", "Times New Roman", serif',
            filter: ready ? 'none' : 'blur(1px)',
            transition: 'filter 0.3s ease',
            pointerEvents: ready ? 'auto' : 'none',
          }}
        >
          {/* Document header */}
          <Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', mb: 3 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <FileText size={18} color={DS_TEXT.brand} />
              <Typography sx={{ fontFamily: 'inherit', fontWeight: 700, color: DS_TEXT.brand, fontSize: '0.75rem', letterSpacing: 1, textTransform: 'uppercase' }}>
                Marktsignal-Bericht
              </Typography>
            </Box>
            <Box sx={{ textAlign: 'right' }}>
              <Typography variant="caption" sx={{ display: 'block', color: DS_TEXT.disabled, fontFamily: 'inherit' }}>Wincasa AG · Zürich</Typography>
              <Typography variant="caption" sx={{ display: 'block', color: DS_TEXT.disabled, fontFamily: 'inherit' }}>{new Date().toLocaleDateString('de-CH')}</Typography>
            </Box>
          </Box>

          <Box sx={{ borderBottom: `2px solid ${DS_TEXT.brand}`, mb: 2.5 }} />

          <Typography sx={{ fontFamily: 'inherit', fontWeight: 700, color: '#0f172a', fontSize: '1.1rem', mb: 0.5 }}>
            Standortintelligenz & Marktsignale
          </Typography>
          <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.muted, fontSize: '0.825rem', mb: 3 }}>
            Objekt-ID: {propertyId} · Generiert: {report?.generatedAt ? new Date(report.generatedAt).toLocaleDateString('de-CH') : new Date().toLocaleDateString('de-CH')} · {signals.length} Signale
          </Typography>

          {/* Sections */}
          {categories.map(cat => {
            const catSignals = signals.filter(s => s.category === cat)
            if (catSignals.length === 0) return null
            const color = SECTION_COLORS[cat]
            const label = SECTION_LABELS[cat]
            return (
              <Box key={cat} sx={{ mb: 3.5 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 1.5, pb: 0.75, borderBottom: `1px solid ${color}22` }}>
                  <Box sx={{ width: 3, height: 16, bgcolor: color, borderRadius: 1, flexShrink: 0 }} />
                  <Typography sx={{ fontFamily: 'inherit', fontWeight: 700, color, fontSize: '0.875rem', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                    {label}
                  </Typography>
                  <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.disabled, fontSize: '0.75rem', ml: 0.5 }}>
                    ({catSignals.length})
                  </Typography>
                </Box>
                {catSignals.map((s, i) => (
                  <Box key={s.id} sx={{ mb: i < catSignals.length - 1 ? 2 : 0, pl: 1.5, borderLeft: `2px solid ${DS_BORDER.default}` }}>
                    <Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 1, mb: 0.5 }}>
                      <Typography sx={{ fontFamily: 'inherit', fontWeight: 700, color: '#0f172a', fontSize: '0.875rem', lineHeight: 1.4 }}>
                        {s.title}
                      </Typography>
                      {s.confidence != null && (
                        <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.muted, fontSize: '0.75rem', flexShrink: 0 }}>
                          KI-Konfidenz: {Math.round(s.confidence * 100)}%
                        </Typography>
                      )}
                    </Box>
                    <Typography sx={{ fontFamily: 'inherit', color: '#374151', fontSize: '0.825rem', lineHeight: 1.6, mb: 0.5 }}>
                      {s.body}
                    </Typography>
                    <Box sx={{ display: 'flex', gap: 2 }}>
                      {s.date && (
                        <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.disabled, fontSize: '0.75rem' }}>
                          {new Date(s.date).toLocaleDateString('de-CH')}
                        </Typography>
                      )}
                      {s.source && (
                        <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.disabled, fontSize: '0.75rem' }}>
                          Quelle: {s.source}
                        </Typography>
                      )}
                    </Box>
                  </Box>
                ))}
              </Box>
            )
          })}

          {signals.length === 0 && (
            <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.disabled, fontSize: '0.875rem', fontStyle: 'italic', textAlign: 'center', py: 4 }}>
              Keine Marktsignale für dieses Objekt verfügbar.
            </Typography>
          )}

          {/* Footer */}
          <Box sx={{ borderTop: `1px solid ${DS_BORDER.default}`, mt: 3, pt: 2 }}>
            <Typography sx={{ fontFamily: 'inherit', color: DS_TEXT.disabled, fontSize: '0.75rem', textAlign: 'center' }}>
              Dieser Bericht wurde automatisch auf Basis von KI-generierten Marktsignalen erstellt. · Wincasa AG
            </Typography>
          </Box>
        </Box>
      </Box>

      {/* Footer actions */}
      <Box sx={{ px: 3, py: 1.5, borderTop: `1px solid ${DS_BORDER.default}`, bgcolor: 'white', display: 'flex', justifyContent: 'flex-end', gap: 1, flexShrink: 0 }}>
        <Button variant="outlined" onClick={onClose} sx={{ textTransform: 'none' }}>
          Schliessen
        </Button>
        <Button
          variant="contained"
          startIcon={<Download size={15} />}
          onClick={handleDownload}
          disabled={!ready}
          sx={{ textTransform: 'none', bgcolor: DS_TEXT.brand, '&:hover': { bgcolor: '#16304d' } }}
        >
          Herunterladen
        </Button>
      </Box>
    </Dialog>
  )
}
