import { useEffect, useState } from 'react'
import { Alert, Box, Button, Chip, CircularProgress, Typography } from '@mui/material'
import { BarChart2, Building2, FileText, Lightbulb, TrendingUp } from 'lucide-react'
import { marketReportService } from '../../services/marketReportService'
import type { MarketReport, SignalCategory } from '../../domain/marketReport'
import { SignalCard } from './SignalCard'
import { BerichtDialog } from './BerichtDialog'

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' },
]

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>
  )
}
