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 generation dialog ─────────────────────────────────────────────────────

type PdfState = 'idle' | 'generating' | 'ready'

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

function BerichtDialog({ open, onClose, report, propertyId }: BerichtDialogProps) {
  const [state, setState] = useState<PdfState>('idle')
  const [progress, setProgress] = useState(0)
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  useEffect(() => {
    if (!open) { setState('idle'); setProgress(0); return }
    setState('generating')
    setProgress(0)
    let p = 0
    timerRef.current = setInterval(() => {
      p += Math.random() * 18 + 8
      if (p >= 100) {
        p = 100
        clearInterval(timerRef.current!)
        setTimeout(() => setState('ready'), 300)
      }
      setProgress(Math.min(100, p))
    }, 200)
    return () => { if (timerRef.current) clearInterval(timerRef.current) }
  }, [open])

  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(`[${s.category.toUpperCase()}] ${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()
  }

  return (
    <Dialog open={open} onClose={state === 'generating' ? undefined : onClose} maxWidth="xs" fullWidth>
      <DialogTitle sx={{ fontWeight: 700, fontSize: '1rem', pb: 1 }}>
        Bericht erstellen
      </DialogTitle>
      <DialogContent>
        {state === 'generating' && (
          <Box sx={{ py: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 2 }}>
              <CircularProgress size={20} />
              <Typography variant="body2" sx={{ color: '#374151' }}>
                PDF-Bericht wird generiert…
              </Typography>
            </Box>
            <LinearProgress
              variant="determinate"
              value={progress}
              sx={{ height: 6, borderRadius: 3, bgcolor: '#e2e8f0', '& .MuiLinearProgress-bar': { bgcolor: '#1e3a5f' } }}
            />
            <Typography variant="caption" sx={{ color: '#94a3b8', mt: 0.75, display: 'block' }}>
              {Math.round(progress)}% — Marktsignale werden aufbereitet
            </Typography>
          </Box>
        )}

        {state === 'ready' && (
          <Box sx={{ py: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 2 }}>
              <CheckCircle size={20} color="#1a7a4a" />
              <Typography variant="body2" sx={{ color: '#166534', fontWeight: 600 }}>
                Bericht ist bereit
              </Typography>
            </Box>
            <Box sx={{ p: 2, bgcolor: '#f8fafc', borderRadius: 1.5, border: '1px solid #e2e8f0', mb: 2 }}>
              <Typography variant="caption" sx={{ color: '#64748b', display: 'block' }}>Dateiname</Typography>
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                Marktsignal-Bericht_{propertyId}.pdf
              </Typography>
              <Typography variant="caption" sx={{ color: '#94a3b8', display: 'block', mt: 0.5 }}>
                {report?.signals.length ?? 0} Signale · {new Date().toLocaleDateString('de-CH')}
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button
                fullWidth
                variant="contained"
                startIcon={<Download size={15} />}
                onClick={handleDownload}
                sx={{ textTransform: 'none', bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#16304d' } }}
              >
                Herunterladen
              </Button>
              <Button fullWidth variant="outlined" onClick={onClose} sx={{ textTransform: 'none' }}>
                Schliessen
              </Button>
            </Box>
          </Box>
        )}
      </DialogContent>
    </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={() => showToast('PDF-Bericht wird generiert…', 'info')}
          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>
          )
        })
      )}
    </Box>
  )
}
