import { useNavigate } from 'react-router'
import { MatchCardCompact } from '../match-card/MatchCardCompact'
import { IntelligenceMatchCard } from '../match-card/IntelligenceMatchCard'
import { buildMatchCardViewModel } from '../../features/matching/matchCardAdapter'
import { useCompareStore } from '../../stores/compareStore'
import { useShortlistStore } from '../../stores/shortlistStore'
import type { UnifiedMatchResult } from '../../domain/unifiedResult'
import type { MatchCardAction } from '../match-card/MatchCardViewModel'

interface Props {
  result: UnifiedMatchResult
  view?: 'list' | 'grid'
}

function getResultTitle(result: UnifiedMatchResult): string {
  if (result.resultType !== 'FUTURE_AVAILABILITY') {
    return result.property?.title ?? result.matchId
  }
  return result.signal?.companyName ?? result.matchId
}

export function UnifiedResultCard({ result, view = 'list' }: Props) {
  const navigate = useNavigate()
  const { addToCompare, removeFromCompare, isInCompare, isFull } = useCompareStore()
  const { openAddDialog } = useShortlistStore()
  const inCompare = isInCompare(result.matchId)

  const actions: MatchCardAction[] = [
    {
      id: 'shortlist',
      label: 'Shortlist',
      actionType: 'SAVE_SHORTLIST',
      variant: 'secondary',
      onClick: () => openAddDialog({
        resultId: result.matchId,
        resultType: result.resultType,
        title: getResultTitle(result),
        matchScore: result.matchScore,
        confidenceScore: result.match.confidenceLevel,
        sourceLabel: result.resultType,
        addedBy: 'admin@ideal-sharing.ch',
      }),
    },
    {
      id: 'compare',
      label: inCompare ? 'Im Vergleich' : 'Vergleichen',
      actionType: 'ADD_COMPARE',
      variant: inCompare ? 'primary' : 'secondary',
      disabled: !inCompare && isFull(),
      onClick: () => {
        if (inCompare) removeFromCompare(result.matchId)
        else addToCompare(result)
      },
    },
    {
      id: 'details',
      label: 'Details →',
      actionType: 'OPEN_DETAIL',
      variant: 'primary',
      onClick: () => navigate(`/demand/results/${result.matchId}`),
    },
  ]

  const vm = buildMatchCardViewModel(result, actions)

  if (view === 'grid') {
    const imageUrl = result.resultType !== 'FUTURE_AVAILABILITY'
      ? result.property.images?.[0]
      : undefined
    const lat = result.resultType !== 'FUTURE_AVAILABILITY'
      ? result.property.location.coordinates?.lat
      : undefined
    const lng = result.resultType !== 'FUTURE_AVAILABILITY'
      ? result.property.location.coordinates?.lng
      : undefined
    const cityLabel = result.resultType !== 'FUTURE_AVAILABILITY'
      ? result.property.location.city
      : result.signal.locationHint ?? undefined

    return (
      <IntelligenceMatchCard
        vm={vm}
        imageUrl={imageUrl}
        lat={lat}
        lng={lng}
        cityLabel={cityLabel}
      />
    )
  }

  return <MatchCardCompact vm={vm} />
}
