import { Box, CircularProgress, Paper, Typography } from '@mui/material'
import { useNavigate, useParams } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { useMatchDetail } from '../../hooks/useMatches'
import { propertyService } from '../../services/propertyService'
import { needService } from '../../services/needService'
import { futureSignalService } from '../../services/futureSignalService'
import { useCompareStore } from '../../stores/compareStore'
import { useShortlistStore } from '../../stores/shortlistStore'
import { AddToShortlistDialog } from '../../components/shortlist'
import { MatchReasonList } from '../../components/match-card/MatchReasonList'
import {
  LocationIntelligencePanel,
  MatchDetailHeader,
  ExecutiveSummaryPanel,
  PropertyOverviewPanel,
  NeedAlignmentPanel,
  ScoreBreakdownPanel,
  TradeoffPanel,
  RiskPanel,
  MissingInformationPanel,
  SourceProvenancePanel,
  FutureAvailabilityContextPanel,
  NextActionsPanel,
} from '../../components/match-detail'
import type { MatchCardReason } from '../../components/match-card/MatchCardViewModel'

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

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

  const { data: match, isLoading } = useMatchDetail(matchId ?? '')

  const isFuture = match?.resultType === 'FUTURE_AVAILABILITY'


  const { data: property = null } = useQuery({
    queryKey: ['property', match?.propertyId],
    queryFn: () => propertyService.getById(match!.propertyId),
    enabled: !!match && !isFuture,
    select: r => r.data ?? null,
  })

  const { data: need = null } = useQuery({
    queryKey: ['need', match?.needId],
    queryFn: () => needService.getById(match!.needId),
    enabled: !!match?.needId,
    select: r => r.data ?? null,
  })

  const { data: signal = null } = useQuery({
    queryKey: ['signal', match?.resultId],
    queryFn: () => futureSignalService.getById(match!.resultId!),
    enabled: !!match && isFuture && !!match.resultId,
    select: r => r.data ?? null,
  })

  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>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            Das gesuchte Match existiert nicht oder wurde entfernt.
          </Typography>
        </Paper>
      </Box>
    )
  }

  const reasons = buildReasons(match)

  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 handleBack = () => navigate(-1)

  const handleShortlist = () => {
    const title = property?.title ?? signal?.companyName ?? signal?.locationHint ?? match.id
    openAddDialog({
      resultId: match.id,
      resultType: match.resultType ?? 'VERIFIED_PORTFOLIO',
      title,
      matchScore: match.matchScore,
      confidenceScore: match.confidenceLevel,
      sourceLabel: property?.sourceLabel ?? match.resultType ?? 'VERIFIED_PORTFOLIO',
      addedBy: 'admin@ideal-sharing.ch',
      propertyId: property?.id,
    })
  }

  return (
    <Box sx={{ px: 3, py: 2 }}>
      <AddToShortlistDialog />
      <MatchDetailHeader
        match={match}
        property={property}
        signal={signal}
        onBack={handleBack}
        onCompare={handleCompare}
        onShortlist={handleShortlist}
      />

      <Box sx={{ display: 'flex', gap: 3, alignItems: 'flex-start' }}>
        {/* Main column */}
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <ExecutiveSummaryPanel match={match} />
          <PropertyOverviewPanel match={match} property={property} signal={signal} />
          <NeedAlignmentPanel match={match} need={need} property={property} />

          {/* Why It Matches — structured from scoreFactors */}
          {reasons.length > 0 && (
            <Paper sx={{ p: 2.5, mb: 2 }}>
              <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} />
          <TradeoffPanel match={match} />
          <RiskPanel match={match} />
          <MissingInformationPanel match={match} />
          <SourceProvenancePanel property={property} />
          {isFuture && <FutureAvailabilityContextPanel match={match} signal={signal} />}
        </Box>

        {/* Sidebar — sticky */}
        <Box sx={{ width: 320, flexShrink: 0, position: 'sticky', top: 24 }}>
          <ScoreBreakdownPanel match={match} />
          <NextActionsPanel
            match={match}
            onCompare={handleCompare}
            onShortlist={handleShortlist}
            onReview={() => {}}
            onReject={() => {}}
          />
        </Box>
      </Box>
    </Box>
  )
}
