import { Box, Chip, Divider, LinearProgress, Paper, Typography } from '@mui/material'
import { CheckCircle, TrendingDown, TrendingUp } from 'lucide-react'
import { useProperties } from '../../hooks/useProperties'
import { useNeeds } from '../../hooks/useNeeds'
import { getCityIntelligence, getMarketRent } from '../../lib/locationIntelligence'
import type { Property } from '../../domain/property'
import { generateSellingArguments, generateWeaknesses } from './negotiationInsightsUtils'
import { DS_TEXT, DS_BG, DS_SURFACE, DS_BORDER } from '../../lib/ds'

interface Props {
  property: Property
}

export function NegotiationInsightsPanel({ property }: Props) {
  const { data: allProperties = [] } = useProperties()
  const { data: needs = [] } = useNeeds()

  const intel = getCityIntelligence(property.location.city)
  const marketRent = getMarketRent(property.location.city, property.assetType)
  const priceDiff = marketRent ? ((property.rentPricePerSqm - marketRent) / marketRent) * 100 : null

  const comparables = allProperties
    .filter(p => p.id !== property.id && p.assetType === property.assetType && p.location.city === property.location.city)

  const avgComparableRent = comparables.length > 0
    ? comparables.reduce((s, p) => s + p.rentPricePerSqm, 0) / comparables.length
    : null

  const matchingNeeds = needs.filter(n =>
    n.assetType === property.assetType &&
    (n.preferredLocations?.some(loc => loc.toLowerCase().includes(property.location.city.toLowerCase())) ?? false)
  )

  const sellingArgs = generateSellingArguments(property)
  const weaknesses = generateWeaknesses(property)
  const strongArgs = sellingArgs.filter(a => a.strength === 'strong')
  const mediumArgs = sellingArgs.filter(a => a.strength === 'medium')

  const priceDiffBg = priceDiff !== null
    ? (Math.abs(priceDiff) < 10 ? DS_SURFACE.success.bg : priceDiff > 0 ? DS_SURFACE.orange.bg : DS_SURFACE.success.bg)
    : DS_BG.page

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>

      {/* ── Price positioning ── */}
      <Paper sx={{ p: 2.5 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 1.5 }}>Preispositionierung</Typography>

        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mb: 1.5 }}>
          <Box sx={{ flex: 1, p: 1.5, bgcolor: DS_BG.page, borderRadius: 1.5, border: `1px solid ${DS_BORDER.default}`, minWidth: 120 }}>
            <Typography variant="caption" color="text.secondary">Ihr Preis</Typography>
            <Typography variant="h6" sx={{ fontWeight: 700, color: DS_TEXT.primary }}>
              CHF {property.rentPricePerSqm}/m²/Jahr
            </Typography>
          </Box>
          {marketRent && (
            <Box sx={{ flex: 1, p: 1.5, bgcolor: DS_BG.page, borderRadius: 1.5, border: `1px solid ${DS_BORDER.default}`, minWidth: 120 }}>
              <Typography variant="caption" color="text.secondary">Marktmedian {property.location.city}</Typography>
              <Typography variant="h6" sx={{ fontWeight: 700, color: DS_TEXT.secondary }}>
                CHF {marketRent}/m²
              </Typography>
            </Box>
          )}
          {avgComparableRent && (
            <Box sx={{ flex: 1, p: 1.5, bgcolor: DS_BG.page, borderRadius: 1.5, border: `1px solid ${DS_BORDER.default}`, minWidth: 120 }}>
              <Typography variant="caption" color="text.secondary">Vergleichsangebote Ø</Typography>
              <Typography variant="h6" sx={{ fontWeight: 700, color: DS_TEXT.secondary }}>
                CHF {Math.round(avgComparableRent)}/m²
              </Typography>
            </Box>
          )}
        </Box>

        {priceDiff !== null && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, p: 1.25, bgcolor: priceDiffBg, borderRadius: 1.5 }}>
            {priceDiff > 0 ? <TrendingUp size={15} color={DS_TEXT.warning} /> : <TrendingDown size={15} color={DS_TEXT.success} />}
            <Typography variant="body2" sx={{ color: priceDiff > 15 ? DS_TEXT.warningDark : priceDiff > 0 ? DS_TEXT.warning : DS_TEXT.success, fontWeight: 500 }}>
              {priceDiff > 15
                ? `Ihr Preis liegt ${Math.round(priceDiff)}% über dem Marktmedian — starke USPs nötig zur Rechtfertigung.`
                : priceDiff > 5
                  ? `Leicht über Marktmedian (+${Math.round(priceDiff)}%) — gut durch Qualität begründbar.`
                  : priceDiff > -5
                    ? 'Im Marktdurchschnitt — gute Ausgangsposition.'
                    : `${Math.round(Math.abs(priceDiff))}% unter Marktmedian — Preiserhöhung oder schnelle Vermietung möglich.`}
            </Typography>
          </Box>
        )}

        {marketRent && (
          <Box sx={{ mt: 1.5 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.25 }}>
              <Typography variant="caption" color="text.secondary">Marktbereich {property.location.city}</Typography>
              <Typography variant="caption" color="text.secondary">
                CHF {Math.round(marketRent * 0.7)}–{Math.round(marketRent * 1.4)}/m²
              </Typography>
            </Box>
            <Box sx={{ position: 'relative', height: 8, bgcolor: DS_BORDER.default, borderRadius: 4 }}>
              <Box sx={{
                position: 'absolute',
                left: `${Math.min(90, Math.max(5, ((property.rentPricePerSqm - marketRent * 0.7) / (marketRent * 0.7)) * 100))}%`,
                top: -2,
                width: 12,
                height: 12,
                borderRadius: '50%',
                bgcolor: DS_TEXT.brand,
                border: '2px solid white',
                boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
              }} />
            </Box>
          </Box>
        )}
      </Paper>

      {/* ── Active demand ── */}
      <Paper sx={{ p: 2.5 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Aktive Nachfrage</Typography>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
          Unternehmen, die aktuell in {property.location.city} suchen
        </Typography>
        {matchingNeeds.length > 0 ? (
          <>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.5 }}>
              <Typography variant="h4" sx={{ fontWeight: 800, color: DS_TEXT.brand }}>{matchingNeeds.length}</Typography>
              <Typography variant="body2" color="text.secondary">aktive Suchprofile für diesen Typ & Standort</Typography>
            </Box>
            {matchingNeeds.slice(0, 4).map(n => (
              <Box key={n.id} sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', py: 0.75, borderBottom: `1px solid ${DS_BORDER.muted}` }}>
                <Box>
                  <Typography variant="caption" sx={{ fontWeight: 500 }}>{n.companyName}</Typography>
                  <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
                    {n.requiredArea?.min ?? 0}–{n.requiredArea?.max ?? 0} m²
                    {n.budgetRange?.maxPerSqm ? ` · max. CHF ${n.budgetRange.maxPerSqm}/m²/Jahr` : ''}
                  </Typography>
                </Box>
                <Chip
                  label={n.status === 'ACTIVE' ? 'Aktiv' : n.status === 'DRAFT' ? 'Entwurf' : n.status}
                  size="small"
                  sx={{
                    bgcolor: n.status === 'ACTIVE' ? DS_SURFACE.success.bg : DS_BG.subtle,
                    color: n.status === 'ACTIVE' ? DS_TEXT.success : DS_TEXT.muted,
                    fontSize: 10, height: 18,
                  }}
                />
              </Box>
            ))}
            {matchingNeeds.length > 4 && (
              <Typography variant="caption" color="text.secondary" sx={{ mt: 0.75, display: 'block' }}>
                + {matchingNeeds.length - 4} weitere Suchprofile
              </Typography>
            )}
          </>
        ) : (
          <Typography variant="body2" color="text.secondary">
            Keine aktiven Suchprofile für diesen Typ und Standort.
          </Typography>
        )}
        {intel && (
          <Box sx={{ mt: 1.5, p: 1.25, bgcolor: DS_BG.page, borderRadius: 1.5 }}>
            <Typography variant="caption" color="text.secondary">
              Ø Vermietungsdauer vergleichbarer Objekte in {property.location.city}:{' '}
              <strong style={{ color: DS_TEXT.brand }}>{intel.avgDaysOnMarket} Tage</strong>
            </Typography>
          </Box>
        )}
      </Paper>

      {/* ── Selling arguments ── */}
      {sellingArgs.length > 0 && (
        <Paper sx={{ p: 2.5 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Verkaufsargumente für das Gespräch</Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
            Stärken dieses Objekts — maßgeschneidert auf typische Mieterwünsche
          </Typography>

          {strongArgs.length > 0 && (
            <Box sx={{ mb: 1.5 }}>
              <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.success, display: 'block', mb: 0.75 }}>
                Starke Argumente
              </Typography>
              {strongArgs.map((arg, i) => (
                <Box key={i} sx={{ display: 'flex', gap: 1, mb: 1 }}>
                  <CheckCircle size={15} color={DS_TEXT.success} style={{ marginTop: 2, flexShrink: 0 }} />
                  <Box>
                    <Typography variant="body2" sx={{ fontWeight: 600 }}>{arg.title}</Typography>
                    <Typography variant="caption" color="text.secondary">{arg.detail}</Typography>
                  </Box>
                </Box>
              ))}
            </Box>
          )}

          {mediumArgs.length > 0 && (
            <Box>
              <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.warning, display: 'block', mb: 0.75 }}>
                Weitere Vorteile
              </Typography>
              {mediumArgs.map((arg, i) => (
                <Box key={i} sx={{ display: 'flex', gap: 1, mb: 0.75 }}>
                  <CheckCircle size={14} color={DS_TEXT.warning} style={{ marginTop: 2, flexShrink: 0 }} />
                  <Box>
                    <Typography variant="body2" sx={{ fontWeight: 500 }}>{arg.title}</Typography>
                    <Typography variant="caption" color="text.secondary">{arg.detail}</Typography>
                  </Box>
                </Box>
              ))}
            </Box>
          )}
        </Paper>
      )}

      {/* ── Proactive weakness handling ── */}
      {weaknesses.length > 0 && (
        <Paper sx={{ p: 2.5 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Schwächen proaktiv adressieren</Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
            Potenzielle Einwände kennen und entkräften — bevor der Interessent fragt
          </Typography>
          {weaknesses.map((w, i) => (
            <Box key={i} sx={{ mb: 1.25 }}>
              <Typography variant="body2" sx={{ fontWeight: 600, color: DS_TEXT.error, mb: 0.25 }}>
                ⚠ {w.issue}
              </Typography>
              <Box sx={{ pl: 1.5, borderLeft: `2px solid ${DS_BORDER.default}` }}>
                <Typography variant="caption" color="text.secondary">→ {w.mitigation}</Typography>
              </Box>
              {i < weaknesses.length - 1 && <Divider sx={{ mt: 1.25 }} />}
            </Box>
          ))}
        </Paper>
      )}

      {/* ── Tenant fit ── */}
      {intel && intel.dominantIndustryClusters.length > 0 && (
        <Paper sx={{ p: 2.5 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Welche Mieter passen?</Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
            Dominant präsente Branchen in {property.location.city} — hohes Match-Potenzial
          </Typography>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75 }}>
            {intel.dominantIndustryClusters.map(c => (
              <Chip key={c} label={c} size="small"
                sx={{ bgcolor: DS_SURFACE.blue.bg, color: DS_TEXT.brand, fontSize: 11, height: 24, fontWeight: 500 }}
              />
            ))}
          </Box>
          <LinearProgress
            variant="determinate"
            value={intel.demandStrength === 'VERY_HIGH' ? 95 : intel.demandStrength === 'HIGH' ? 75 : intel.demandStrength === 'MEDIUM' ? 50 : 25}
            sx={{ mt: 1.5, height: 6, borderRadius: 3, bgcolor: DS_BG.subtle, '& .MuiLinearProgress-bar': { bgcolor: DS_TEXT.brand } }}
          />
          <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5, display: 'block' }}>
            Nachfragestärke: {' '}
            <strong>{{ LOW: 'Gering', MEDIUM: 'Mittel', HIGH: 'Hoch', VERY_HIGH: 'Sehr hoch' }[intel.demandStrength]}</strong>
          </Typography>
        </Paper>
      )}
    </Box>
  )
}
