import { useEffect, useRef, useState } from 'react'
import { Alert, Box, Button, Chip, CircularProgress, Dialog, DialogContent, DialogTitle, LinearProgress, Typography } from '@mui/material'
import { BarChart2, Building2, CheckCircle, Download, FileText, Lightbulb, TrendingUp } from 'lucide-react'
import { marketReportService } from '../../services/marketReportService'
import type { MarketReport, PropertyMarketSignal, SignalCategory } from '../../domain/marketReport'

interface Props {
  propertyId: string
}

const SECTION_CONFIG: { category: SignalCategory; label: string; icon: React.ReactNode; color: string }[] = [
  { category: 'development', label: 'Entwicklungsnews', icon: <Building2 size={16} />, color: '#1e3a5f' },
  { category: 'demand',      label: 'Nachfrage 5 km',   icon: <TrendingUp size={16} />, color: '#1a7a4a' },
  { category: 'supply',      label: 'Angebot 5 km',     icon: <BarChart2 size={16} />,  color: '#b45309' },
  { category: 'negotiation', label: 'Verhandlungshinweise', icon: <Lightbulb size={16} />, color: '#7c3aed' },
]

function SignalCard({ signal }: { signal: PropertyMarketSignal }) {
  return (
    <Box
      sx={{
        p: 1.75,
        mb: 1.25,
        borderRadius: 1.5,
        border: '1px solid #e2e8f0',
        bgcolor: 'white',
      }}
    >
      <Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 1, mb: 0.75 }}>
        <Typography variant="body2" sx={{ fontWeight: 600, color: '#0f172a', lineHeight: 1.35 }}>
          {signal.title}
        </Typography>
        {signal.confidence != null && (
          <Chip
            label={`${Math.round(signal.confidence * 100)}%`}
            size="small"
            sx={{ fontSize: '0.62rem', height: 18, flexShrink: 0, bgcolor: '#f0f9ff', color: '#0369a1', border: '1px solid #bae6fd' }}
          />
        )}
      </Box>

      <Typography variant="caption" sx={{ color: '#374151', lineHeight: 1.5, display: 'block', mb: signal.source || signal.confidence ? 1 : 0 }}>
        {signal.body}
      </Typography>

      {signal.confidence != null && (
        <Box sx={{ mb: 0.75 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.25 }}>
            <Typography variant="caption" sx={{ color: '#94a3b8', fontSize: '0.62rem' }}>KI-Konfidenz</Typography>
            <Typography variant="caption" sx={{ color: '#64748b', fontSize: '0.62rem' }}>{Math.round(signal.confidence * 100)}%</Typography>
          </Box>
          <LinearProgress
            variant="determinate"
            value={signal.confidence * 100}
            sx={{
              height: 3,
              borderRadius: 2,
              bgcolor: '#e2e8f0',
              '& .MuiLinearProgress-bar': { bgcolor: signal.confidence >= 0.8 ? '#1a7a4a' : signal.confidence >= 0.6 ? '#d97706' : '#64748b' },
            }}
          />
        </Box>
      )}

      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        {signal.date && (
          <Typography variant="caption" sx={{ color: '#94a3b8', fontSize: '0.62rem' }}>
            {new Date(signal.date).toLocaleDateString('de-CH')}
          </Typography>
        )}
        {signal.source && (
          <Box
            component={signal.sourceUrl ? 'a' : 'span'}
            href={signal.sourceUrl}
            target="_blank"
            rel="noopener noreferrer"
            sx={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 0.375,
              fontSize: '0.62rem',
              color: signal.sourceUrl ? '#1e3a5f' : '#94a3b8',
              textDecoration: 'none',
              '&:hover': signal.sourceUrl ? { textDecoration: 'underline' } : {},
            }}
          >
            <FileText size={10} />
            {signal.source}
          </Box>
        )}
      </Box>
    </Box>
  )
}

// ── PDF preview dialog ────────────────────────────────────────────────────────

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
}

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
      PaperProps={{ sx: { height: '88vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' } }}
    >
      {/* Header */}
      <Box sx={{ px: 3, py: 1.5, borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
        <Box>
          <Typography variant="caption" sx={{ color: '#64748b', 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="#1a7a4a" />
            <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 #e2e8f0', bgcolor: '#f8fafc', 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: '#94a3b8', ml: 'auto' }}>{Math.round(progress)}%</Typography>
          </Box>
          <LinearProgress
            variant="determinate"
            value={progress}
            sx={{ height: 4, borderRadius: 2, bgcolor: '#e2e8f0', '& .MuiLinearProgress-bar': { bgcolor: '#1e3a5f' } }}
          />
        </Box>
      )}

      {/* PDF Preview */}
      <Box sx={{ flex: 1, overflow: 'auto', bgcolor: '#f1f5f9', p: 3 }}>
        <Box
          sx={{
            bgcolor: 'white',
            borderRadius: 1.5,
            border: '1px solid #cbd5e1',
            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="#1e3a5f" />
              <Typography sx={{ fontFamily: 'inherit', fontWeight: 700, color: '#1e3a5f', fontSize: '0.75rem', letterSpacing: 1, textTransform: 'uppercase' }}>
                Marktsignal-Bericht
              </Typography>
            </Box>
            <Box sx={{ textAlign: 'right' }}>
              <Typography variant="caption" sx={{ display: 'block', color: '#94a3b8', fontFamily: 'inherit' }}>Wincasa AG · Zürich</Typography>
              <Typography variant="caption" sx={{ display: 'block', color: '#94a3b8', fontFamily: 'inherit' }}>{new Date().toLocaleDateString('de-CH')}</Typography>
            </Box>
          </Box>

          <Box sx={{ borderBottom: '2px solid #1e3a5f', 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: '#64748b', 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: '#94a3b8', 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 #e2e8f0` }}>
                    <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: '#64748b', 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: '#94a3b8', fontSize: '0.75rem' }}>
                          {new Date(s.date).toLocaleDateString('de-CH')}
                        </Typography>
                      )}
                      {s.source && (
                        <Typography sx={{ fontFamily: 'inherit', color: '#94a3b8', fontSize: '0.75rem' }}>
                          Quelle: {s.source}
                        </Typography>
                      )}
                    </Box>
                  </Box>
                ))}
              </Box>
            )
          })}

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

          {/* Footer */}
          <Box sx={{ borderTop: '1px solid #e2e8f0', mt: 3, pt: 2 }}>
            <Typography sx={{ fontFamily: 'inherit', color: '#94a3b8', 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 #e2e8f0', 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: '#1e3a5f', '&:hover': { bgcolor: '#16304d' } }}
        >
          Herunterladen
        </Button>
      </Box>
    </Dialog>
  )
}

// ── Main tab component ────────────────────────────────────────────────────────

export function PropertyMarketSignalsTab({ propertyId }: Props) {
  const [report, setReport] = useState<MarketReport | null>(null)
  const [loading, setLoading] = useState(true)
  const [dialogOpen, setDialogOpen] = useState(false)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    marketReportService.getByProperty(propertyId).then(r => {
      if (!cancelled) { setReport(r); setLoading(false) }
    })
    return () => { cancelled = true }
  }, [propertyId])

  if (loading) {
    return (
      <Box sx={{ p: 3, display: 'flex', justifyContent: 'center' }}>
        <CircularProgress size={24} />
      </Box>
    )
  }

  return (
    <Box sx={{ p: 2.5 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2.5 }}>
        <Box>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, color: '#0f172a' }}>
            Marktsignale & Standortintelligenz
          </Typography>
          {report?.generatedAt && (
            <Typography variant="caption" sx={{ color: '#94a3b8' }}>
              Generiert {new Date(report.generatedAt).toLocaleDateString('de-CH')}
            </Typography>
          )}
        </Box>
        <Button
          variant="outlined"
          size="small"
          startIcon={<FileText size={14} />}
          onClick={() => setDialogOpen(true)}
          sx={{ textTransform: 'none', fontSize: '0.8125rem' }}
        >
          Bericht erstellen
        </Button>
      </Box>

      {!report ? (
        <Alert severity="info" sx={{ fontSize: '0.8125rem' }}>
          Für dieses Objekt liegen noch keine KI-generierten Marktsignale vor.
        </Alert>
      ) : (
        SECTION_CONFIG.map(({ category, label, icon, color }) => {
          const signals = report.signals.filter(s => s.category === category)
          if (signals.length === 0) return null
          return (
            <Box key={category} sx={{ mb: 3 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 1.25 }}>
                <Box sx={{ color }}>{icon}</Box>
                <Typography variant="body2" sx={{ fontWeight: 700, color }}>
                  {label}
                </Typography>
                <Chip
                  label={signals.length}
                  size="small"
                  sx={{ height: 18, fontSize: '0.65rem', bgcolor: '#f1f5f9', color: '#64748b' }}
                />
              </Box>
              {signals.map(s => <SignalCard key={s.id} signal={s} />)}
            </Box>
          )
        })
      )}

      {dialogOpen && (
        <BerichtDialog
          onClose={() => setDialogOpen(false)}
          report={report}
          propertyId={propertyId}
        />
      )}
    </Box>
  )
}
