import { Box, Button, Chip, CircularProgress, Paper, Typography } from '@mui/material'
import { ArrowLeft } from 'lucide-react'
import { useNavigate, useParams } from 'react-router'
import { useCompareStore } from '../../stores/compareStore'
import { usePipelineStore } from '../../stores/pipelineStore'
import { AddToPipelineDialog } from '../../components/shortlist'
import { MatchReasonList } from '../../components/match-card/MatchReasonList'
import { PropertyMap } from '../../components/shared'
import { getCityIntelligence } from '../../lib/locationIntelligence'
import {
  LocationIntelligencePanel,
  ExecutiveSummaryPanel,
  NeedAlignmentPanel,
  ScoreBreakdownPanel,
  TradeoffPanel,
  RiskPanel,
  MissingInformationPanel,
  FutureAvailabilityContextPanel,
  NextActionsPanel,
} 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 { MatchDetailPropertySections } from '../../components/match-detail/MatchDetailPropertySections'

// ── Match helpers ──────────────────────────────────────────────────────────────

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

const RESULT_TYPE_META: Record<string, { label: string; color: string }> = {
  VERIFIED_PORTFOLIO:  { label: 'Verified Portfolio', color: '#1e3a5f' },
  EXTERNAL_MARKET:     { label: 'Direktinserat',      color: '#d97706' },
  MAISON_WORK:         { label: 'Maison Work',        color: '#0369a1' },
  FUTURE_AVAILABILITY: { label: 'Future Availability', color: '#7c3aed' },
}

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


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

  const { match, property, need, signal, isLoading, isFuture } = useMatchDetailData(matchId ?? '')

  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 ?? '–'
  // Tax calculator — only shown when AI evaluated taxEnvironment
  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 handleCompare = () => {
    if (match && !isFuture && property) {
      addToCompare({
        resultType: property.resultType === 'EXTERNAL_MARKET' ? 'EXTERNAL_MARKET' : 'VERIFIED_PORTFOLIO',
        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,
    })
  }

  // Key facts for the strip below the hero
  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 ?? '–' },
  ]

  return (
    <Box sx={{ bgcolor: '#f1f5f9', minHeight: '100vh' }}>
      <AddToPipelineDialog />

      {/* Sticky back nav */}
      <Box sx={{
        px: 3, py: 1.25, bgcolor: 'white', borderBottom: '1px solid #e2e8f0',
        position: 'sticky', top: 0, zIndex: 100,
        display: 'flex', alignItems: 'center', gap: 2,
      }}>
        <Button
          startIcon={<ArrowLeft size={15} />}
          onClick={() => navigate(-1)}
          size="small"
          sx={{ color: '#64748b', fontWeight: 500, textTransform: 'none' }}
        >
          Zurück zu Resultaten
        </Button>
        {isFuture && (
          <Chip label="Future Availability Signal" 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}
      />

      {/* Main content */}
      <Box sx={{ px: { xs: 1.5, sm: 3 }, py: { xs: 2, sm: 3 }, display: 'flex', flexDirection: { xs: 'column', lg: 'row' }, gap: 3, alignItems: 'flex-start' }}>

        {/* Main column */}
        <Box sx={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
          <ExecutiveSummaryPanel match={match} />
          <NeedAlignmentPanel match={match} need={need} property={property} />

          {/* ── Property Details ── */}
          {!isFuture && property && <MatchDetailPropertySections property={property} match={match} />}

          {reasons.length > 0 && (
            <Paper sx={{ p: 2.5 }}>
              <Typography variant="h6" sx={{ fontWeight: 700, mb: 1.5 }}>Warum dieses Match</Typography>
              <MatchReasonList reasons={reasons} maxItems={3} />
              {match.negativeFactors.length > 0 && (
                <Box sx={{ mt: 1.5 }}>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block', mb: 0.75 }}>
                    Schwächere Faktoren
                  </Typography>
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                    {match.negativeFactors.slice(0, 3).map((f, i) => (
                      <Typography key={i} variant="body2" color="text.secondary">
                        · {f.criterion}: {f.explanation}
                      </Typography>
                    ))}
                  </Box>
                </Box>
              )}
            </Paper>
          )}

          <LocationIntelligencePanel property={property} />

          {/* Map — always show when image was the hero above */}
          {!isFuture && property?.images?.[0] && property?.location?.coordinates && (
            <Paper sx={{ overflow: 'hidden', p: 0 }}>
              <Box sx={{ px: 2.5, pt: 2, pb: 1 }}>
                <Typography variant="h6" sx={{ fontWeight: 700 }}>Standort</Typography>
                <Typography variant="caption" color="text.secondary">
                  {property.address.street} {property.address.houseNumber}, {property.address.postalCode} {property.address.city}
                </Typography>
              </Box>
              <PropertyMap
                lat={property.location.coordinates.lat}
                lng={property.location.coordinates.lng}
                label={property.title}
                height={220}
              />
            </Paper>
          )}

          <TradeoffPanel match={match} />
          <RiskPanel match={match} />
          <MissingInformationPanel match={match} />

          {isFuture && <FutureAvailabilityContextPanel match={match} signal={signal} />}
        </Box>

        {/* Sidebar */}
        <Box sx={{ width: { xs: '100%', lg: 320 }, flexShrink: 0, position: { xs: 'static', lg: 'sticky' }, top: 64, display: 'flex', flexDirection: 'column', gap: 2 }}>
          <ScoreBreakdownPanel match={match} taxCalculatorUrl={taxCalculatorUrl} isFuture={isFuture} signal={signal} />
          <NextActionsPanel
            match={match}
            onCompare={handleCompare}
            onShortlist={handleShortlist}
            onReview={() => {}}
            onReject={() => {}}
          />
        </Box>
      </Box>
    </Box>
  )
}
