import { InquiryQuickDialog } from '../../components/match-detail/InquiryQuickDialog'
import { Box, Button, Chip, CircularProgress, Paper, Typography } from '@mui/material'
import { AlertTriangle, ArrowLeft } from 'lucide-react'
import { useNavigate, useParams } from 'react-router'
import { useCompareStore } from '../../stores/compareStore'
import { usePipelineStore } from '../../stores/pipelineStore'
import { useInquiryStore } from '../../stores/inquiryStore'
import { AddToPipelineDialog } from '../../components/shortlist'
import { MatchReasonList } from '../../components/match-card/MatchReasonList'
import { getCityIntelligence, lookupCityCoords } from '../../lib/locationIntelligence'
import { NextActionsPanel, FitOutCostPanel, FitOutAdvicePanel, MarketPricePanel } from '../../components/match-detail'
import type { MatchCardReason } from '../../components/match-card/MatchCardViewModel'
import { useMatchDetailData } from '../../hooks/useMatchDetailData'
import { useMatchDetail } from '../../hooks/useMatches'
import { MatchDetailHero } from '../../components/match-detail/MatchDetailHero'
import { MatchDetailScoreBreakdown } from '../../components/match-detail/MatchDetailScoreBreakdown'
import { RESULT_TYPE_META, DS_TEXT, DS_SURFACE, DS_BORDER, DS_BG } from '../../lib/ds'

// ── helpers ───────────────────────────────────────────────────────────────────

const HARD_CRITERIA = new Set(['area', 'location', 'budget', 'timing'])

function buildReasons(match: NonNullable<ReturnType<typeof useMatchDetail>['data']>): MatchCardReason[] {
  return match.positiveFactors.slice(0, 3).map(f => ({
    type: (HARD_CRITERIA.has(f.criterion) ? 'HARD_FACT' : 'SOFT_FACTOR') as MatchCardReason['type'],
    label: f.criterion.charAt(0).toUpperCase() + f.criterion.slice(1),
    explanation: f.explanation,
    score: f.score,
  }))
}

// ── page ──────────────────────────────────────────────────────────────────────

export default function MatchDetail() {
  const { matchId } = useParams<{ matchId: string }>()
  const navigate = useNavigate()
  const { addToCompare } = useCompareStore()
  const { openSavedDialog } = usePipelineStore()
  const { openInquiryDialog } = useInquiryStore()

  const { match, property, need, signal, isLoading, isFuture } = useMatchDetailData(matchId ?? '')
  const detailUnit = property?.units?.find(u => u.id === match?.unitId)

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
        <CircularProgress />
      </Box>
    )
  }

  if (!match) {
    return (
      <Box sx={{ px: 3, py: 4 }}>
        <Paper sx={{ p: 4, textAlign: 'center' }}>
          <Typography variant="h6" color="text.secondary">Match nicht gefunden</Typography>
        </Paper>
      </Box>
    )
  }

  const reasons = buildReasons(match)
  const rt = RESULT_TYPE_META[match.resultType ?? 'VERIFIED_PORTFOLIO'] ?? { label: '–', color: '#64748b' }

  const title = property?.title ?? signal?.companyName ?? signal?.locationHint ?? '–'
  const city = property?.location?.city
  const location = city
    ? `${city}${property?.location?.district ? `, ${property.location.district}` : ''}`
    : signal?.locationHint ?? '–'

  const allFactors = [...match.positiveFactors, ...(match.negativeFactors ?? [])]
  const hasTaxFactor = allFactors.some(f => f.criterion === 'taxEnvironment')
  const cityIntel = city ? getCityIntelligence(city) : null
  const taxCalculatorUrl = hasTaxFactor ? (cityIntel?.taxCalculatorUrl ?? undefined) : undefined

  const searchCenter = need?.preferredLocations?.[0] ? lookupCityCoords(need.preferredLocations[0]) : null
  const searchLabel = need?.preferredLocations?.[0]

  const topTradeoff = match.tradeoffs?.[0] ?? match.tradeOffs?.[0]
  const summary = match.explainabilitySummary || `${match.matchStrength}-Match mit ${match.matchScore} Punkten.`

  const handleCompare = () => {
    if (match && !isFuture && property) {
      addToCompare({
        resultType: (property.resultType ?? 'VERIFIED_PORTFOLIO') as 'VERIFIED_PORTFOLIO' | 'MAISON_WORK',
        matchId: match.id, needId: match.needId, matchScore: match.matchScore, match, property,
      })
    } else if (match && isFuture && signal) {
      addToCompare({
        resultType: 'FUTURE_AVAILABILITY',
        matchId: match.id, needId: match.needId, matchScore: match.matchScore, match, signal,
      })
    }
    navigate('/demand/compare')
  }

  const handleShortlist = () => {
    openSavedDialog({
      resultId: match.id,
      resultType: match.resultType ?? 'VERIFIED_PORTFOLIO',
      title: property?.title ?? signal?.companyName ?? signal?.locationHint ?? match.id,
      matchScore: match.matchScore,
      location: property?.location?.city,
      areaLabel: property?.areaSqm ? `${property.areaSqm.toLocaleString('de-CH')} m²` : undefined,
      rentLabel: property?.rentPricePerSqm ? `CHF ${property.rentPricePerSqm}/m²/Jahr` : undefined,
    })
  }

  const keyFacts = isFuture ? [
    { label: 'Flächenschätzung', value: signal?.areaSqmEstimate ? `~${signal.areaSqmEstimate.toLocaleString('de-CH')} m²` : '–' },
    { label: 'Zeithorizont', value: signal?.timeHorizonMonths ? `~${signal.timeHorizonMonths} Monate` : '–' },
    { label: 'Wahrscheinlichkeit', value: signal?.probability ? `${Math.round(signal.probability * 100)}%` : '–' },
  ] : [
    { label: 'Nutzfläche', value: property?.areaSqm ? `${property.areaSqm.toLocaleString('de-CH')} m²` : '–' },
    { label: 'Miete/m²/Jahr', value: property?.rentPricePerSqm ? `CHF ${property.rentPricePerSqm}` : '–' },
    { label: 'Verfügbar ab', value: property?.availabilityDate ?? '–' },
    { label: 'Nutzungsart', value: property?.assetType ?? '–' },
    ...(property?.hardFacts?.fitOut ? [{
      label: 'Ausbaustandard',
      value: (() => {
        const LABELS: Record<string, string> = { SHELL: 'Rohbau', BASIC: 'Basisausbau', FULL: 'Vollausbau', PREMIUM: 'Premiumausbau' }
        const base = LABELS[property.hardFacts!.fitOut!] ?? property.hardFacts!.fitOut!
        const mab = property.hardFacts!.mieterausbaubeitragPerSqm
        return mab ? `${base} + CHF ${mab} MAB` : base
      })(),
    }] : []),
  ]

  return (
    <Box sx={{ bgcolor: DS_BG.page, minHeight: '100vh' }}>
      <AddToPipelineDialog />
      <InquiryQuickDialog />

      {/* Sticky back nav */}
      <Box sx={{
        px: 3, py: 1.25, bgcolor: 'white', borderBottom: `1px solid ${DS_BORDER.default}`,
        position: 'sticky', top: 0, zIndex: 100,
        display: 'flex', alignItems: 'center', gap: 2,
      }}>
        <Button
          startIcon={<ArrowLeft size={15} />}
          onClick={() => navigate(-1)}
          size="small"
          sx={{ color: DS_TEXT.muted, fontWeight: 500, textTransform: 'none' }}
        >
          Zurück zu Resultaten
        </Button>
        {isFuture && (
          <Chip
            label="Zukunftssignal"
            size="small"
            sx={{ bgcolor: '#faf5ff', color: '#7c3aed', fontWeight: 600 }}
          />
        )}
      </Box>

      <MatchDetailHero
        match={match}
        property={property ?? undefined}
        signal={signal}
        isFuture={isFuture}
        title={title}
        location={location}
        rt={rt}
        keyFacts={keyFacts}
        onCompare={handleCompare}
        onShortlist={handleShortlist}
        searchCenterLat={searchCenter?.lat}
        searchCenterLng={searchCenter?.lng}
        searchRadiusKm={need?.searchRadius}
        searchLabel={searchLabel}
      />

      {/* ── Main content ── */}
      <Box sx={{ maxWidth: { sm: 700, md: 860, lg: 1000, xl: 1100 }, mx: 'auto', px: { xs: 1.5, sm: 3 }, py: { xs: 2, sm: 3 }, display: 'flex', flexDirection: 'column', gap: 2 }}>

        {/* ── Section A: Warum dieser Match? ── */}
        <Paper sx={{ p: 2.5 }}>
          <Typography variant="h6" sx={{ fontWeight: 700, mb: 1.25 }}>Warum dieser Match?</Typography>
          <Typography variant="body2" sx={{ color: DS_TEXT.secondary, mb: reasons.length > 0 ? 1.5 : 0, lineHeight: 1.65 }}>
            {summary}
          </Typography>
          {reasons.length > 0 && <MatchReasonList reasons={reasons} maxItems={3} />}
          {topTradeoff && (
            <Box sx={{
              mt: 1.5, display: 'flex', gap: 0.875, alignItems: 'flex-start',
              bgcolor: DS_SURFACE.warning.bg, border: `1px solid ${DS_SURFACE.warning.border}`,
              borderRadius: 1.5, px: 1.5, py: 1,
            }}>
              <AlertTriangle size={14} color={DS_TEXT.warning} style={{ marginTop: 3, flexShrink: 0 }} />
              <Box>
                <Typography variant="caption" sx={{ fontWeight: 700, color: DS_TEXT.warning, display: 'block', mb: 0.25 }}>
                  Hauptabwägung
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {topTradeoff.concern}
                </Typography>
              </Box>
            </Box>
          )}
        </Paper>

        {/* ── Section B: Nächste Aktion ── */}
        <NextActionsPanel
          match={match}
          onCompare={handleCompare}
          onPipeline={handleShortlist}
          onInquire={() => openInquiryDialog({
            propertyTitle: title,
            location,
            areaLabel: property?.areaSqm ? `${property.areaSqm.toLocaleString('de-CH')} m²` : undefined,
            rentLabel: property?.rentPricePerSqm ? `CHF ${property.rentPricePerSqm}/m²/Jahr` : undefined,
            matchScore: match.matchScore,
          })}
        />

        {/* ── Section C: Reale Jahresbelastung (alle fitOut-Werte) ── */}
        {!isFuture && property?.hardFacts?.fitOut && (
          <FitOutCostPanel
            fitOut={property.hardFacts.fitOut}
            areaSqm={property.areaSqm}
            mabPerSqm={property.hardFacts.mieterausbaubeitragPerSqm ?? 0}
            rentPricePerSqm={property.rentPricePerSqm}
            fitOutByLandlord={property.hardFacts.fitOutByLandlord}
          />
        )}

        {/* ── KI-Ausbauempfehlung: nur wenn Mieter ausbaut (SHELL/BASIC, kein Vermieter-Übernahme) ── */}
        {!isFuture && property?.hardFacts?.fitOut
          && !property.hardFacts.fitOutByLandlord
          && (property.hardFacts.fitOut === 'SHELL' || property.hardFacts.fitOut === 'BASIC') && (
          <FitOutAdvicePanel
            fitOut={property.hardFacts.fitOut}
            areaSqm={property.areaSqm}
            mabPerSqm={property.hardFacts.mieterausbaubeitragPerSqm ?? 0}
            rentPricePerSqm={property.rentPricePerSqm}
            requiredFitOut={need?.requiredFitOut}
            tenantBudgetPerSqm={need?.fitOutBudgetMaxPerSqm}
          />
        )}

        {/* ── Marktpreis-Einschätzung (Angebot vs. Markt; bei Pre-Market inkl. Zukunftspreis) ── */}
        {property?.location?.city && property.rentPricePerSqm > 0 && (
          <MarketPricePanel
            city={property.location.city}
            assetType={property.assetType}
            askingRentPerSqm={detailUnit?.rentPricePerSqm ?? property.rentPricePerSqm}
            futureRentPerSqm={isFuture ? detailUnit?.expectedRentPerSqm : undefined}
          />
        )}

        {/* ── Full analysis toggle + expanded panels ── */}
        <MatchDetailScoreBreakdown
          match={match}
          property={property}
          need={need}
          signal={signal}
          isFuture={isFuture}
          taxCalculatorUrl={taxCalculatorUrl}
        />
      </Box>
    </Box>
  )
}
