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

interface Props {
  propertyId: string
}

const STATIC_SECTIONS: { category: SignalCategory; label: string; icon: React.ReactNode; color: string }[] = [
  { category: 'development', label: 'Entwicklungsnews', icon: <Building2 size={16} />, color: '#152642' },
  { category: 'negotiation', label: 'Verhandlungshinweise', icon: <Lightbulb size={16} />, color: '#7c3aed' },
]

export function PropertyMarketSignalsTab({ propertyId }: Props) {
  const { data: report = null, isLoading: loading } = useMarketReport(propertyId)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [radius, setRadius] = useState(5)

  const dynamicSections: { category: SignalCategory; label: string; icon: React.ReactNode; color: string }[] = [
    { category: 'demand', label: `Nachfrage ${radius} km`, icon: <TrendingUp size={16} />, color: '#1a7a4a' },
    { category: 'supply', label: `Angebot ${radius} km`,   icon: <BarChart2 size={16} />,  color: '#b45309' },
  ]

  const sectionConfig = [
    STATIC_SECTIONS[0],
    dynamicSections[0],
    dynamicSections[1],
    STATIC_SECTIONS[1],
  ]

  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>
      ) : (
        <>
          {report.kpis && (
            <MarketKpiPanel
              baseKpis={report.kpis}
              assetTypeLabel={report.assetTypeLabel}
              radius={radius}
              onRadiusChange={setRadius}
            />
          )}

          {sectionConfig.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>
  )
}
