import { useState, useMemo, useEffect } from 'react'
import { Box, Button, Typography } from '@mui/material'
import { Zap } from 'lucide-react'
import { useNavigate, useLocation } from 'react-router'
import { useQueryClient } from '@tanstack/react-query'
import { useUnifiedResults } from '../../hooks/useUnifiedResults'
import { useNeeds } from '../../hooks/useNeeds'
import {
  FeedEmptyState,
  FeedSkeleton,
  ResultFeedHeader,
  ResultFilterBar,
  UnifiedResultFeed,
} from '../../components/results'
import { AddToPipelineDialog } from '../../components/shortlist'
import { InquiryQuickDialog } from '../../components/match-detail/InquiryQuickDialog'
import { ErrorState } from '../../components/ui'
import { useSessionStore } from '../../stores/sessionStore'
import type { UnifiedMatchResult } from '../../domain/unifiedResult'

type FilterSource = 'ALL' | 'PLATFORM' | 'MAISON_WORK'
type SortBy = 'score' | 'rent' | 'area'

function sortResults(results: UnifiedMatchResult[], sortBy: SortBy): UnifiedMatchResult[] {
  return [...results].sort((a, b) => {
    if (sortBy === 'score') return b.matchScore - a.matchScore
    const propA = a.resultType !== 'FUTURE_AVAILABILITY' ? (a as { property: { rentPricePerSqm: number; areaSqm: number } }).property : null
    const propB = b.resultType !== 'FUTURE_AVAILABILITY' ? (b as { property: { rentPricePerSqm: number; areaSqm: number } }).property : null
    if (sortBy === 'rent') return (propA?.rentPricePerSqm ?? 0) - (propB?.rentPricePerSqm ?? 0)
    if (sortBy === 'area') return (propB?.areaSqm ?? 0) - (propA?.areaSqm ?? 0)
    return 0
  })
}

export default function Results() {
  const navigate = useNavigate()
  const location = useLocation()
  const queryClient = useQueryClient()
  const { currentUser } = useSessionStore()
  const [filterSource, setFilterSource] = useState<FilterSource>('ALL')
  const [sortBy, setSortBy] = useState<SortBy>('score')
  const [showFutureAvailability, setShowFutureAvailability] = useState(true)
  const [showOwnProperties, setShowOwnProperties] = useState(true)
  const [view, setView] = useState<'list' | 'grid'>(() =>
    (localStorage.getItem('view-results') as 'list' | 'grid') ?? 'list'
  )

  // When coming from NeedBuilder, invalidate so the freshly created need is included
  const activeNeedIdFromNav = (location.state as { activeNeedId?: string } | null)?.activeNeedId

  const { data: allNeeds = [] } = useNeeds({
    refetchOnMount: activeNeedIdFromNav ? 'always' : true,
    gcTime: 0,
  })

  // Nav ID (from NeedBuilder) takes priority; otherwise first named need
  const effectiveNeedId = activeNeedIdFromNav ?? allNeeds.find(n => n.companyName !== 'Neue Suche')?.id

  const activeNeed = allNeeds.find(n => n.id === effectiveNeedId) ?? allNeeds[0]

  // Invalidate when navigating from NeedBuilder — must be in an effect, not render body
  useEffect(() => {
    if (activeNeedIdFromNav) {
      queryClient.invalidateQueries({ queryKey: ['needs'] })
    }
  }, [activeNeedIdFromNav, queryClient])

  const needsLoading = allNeeds.length === 0 && !activeNeedIdFromNav
  const { data: results = [], isLoading, error } = useUnifiedResults(needsLoading ? undefined : effectiveNeedId)

  const isStaff = currentUser?.role === 'PROPERTY_MANAGER' || currentUser?.role === 'ORGANIZATION_ADMIN'

  // Counts over the full result set — single pass, stable across filter changes
  const { platformCount, maisonWorkCount, futureCount } = useMemo(() => {
    let platform = 0, maison = 0, future = 0
    for (const r of results) {
      if (r.resultType === 'VERIFIED_PORTFOLIO') platform++
      else if (r.resultType === 'MAISON_WORK') maison++
      else if (r.resultType === 'FUTURE_AVAILABILITY') future++
    }
    return { platformCount: platform, maisonWorkCount: maison, futureCount: future }
  }, [results])

  // Filter + sort in one memo — only reruns when inputs change
  const sorted = useMemo(() => {
    const filtered = results.filter(r => {
      if (r.resultType === 'FUTURE_AVAILABILITY') return showFutureAvailability
      if (r.resultType === 'VERIFIED_PORTFOLIO') {
        if (!showOwnProperties) return false
        return filterSource === 'ALL' || filterSource === 'PLATFORM'
      }
      if (filterSource === 'ALL') return true
      return r.resultType === filterSource
    })
    return sortResults(filtered, sortBy)
  }, [results, filterSource, sortBy, showFutureAvailability, showOwnProperties])


  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <AddToPipelineDialog />
      <InquiryQuickDialog />
      <ResultFeedHeader
        total={sorted.length}
        platformCount={platformCount}
        maisonWorkCount={maisonWorkCount}
        futureCount={futureCount}
        view={view}
        onViewChange={v => { setView(v); localStorage.setItem('view-results', v) }}
      />

      <Box sx={{ flex: 1, overflowY: 'auto', px: 3, py: 3, pb: 10 }}>

        {/* Aktive Suche */}
        {activeNeed && (
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 2, bgcolor: '#eff6ff', border: '1px solid #bfdbfe', borderRadius: 1.5, px: 2, py: 1.25, mb: 2 }}>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: '4px 16px', alignItems: 'center' }}>
              <Typography variant="caption" sx={{ fontWeight: 700, color: '#152642' }}>
                {activeNeed.companyName}
              </Typography>
              <Typography variant="caption" color="text.secondary">{activeNeed.assetType}</Typography>
              <Typography variant="caption" color="text.secondary">{activeNeed.requiredArea.min}–{activeNeed.requiredArea.max} m²</Typography>
              <Typography variant="caption" color="text.secondary">{activeNeed.preferredLocations.join(', ')}</Typography>
              {activeNeed.budgetRange?.maxPerSqm > 0 && (
                <Typography variant="caption" color="text.secondary">max. CHF {activeNeed.budgetRange.maxPerSqm}/m²/J</Typography>
              )}
            </Box>
            <Button size="small" variant="text" onClick={() => navigate('/demand/ai-search')}
              sx={{ color: '#152642', flexShrink: 0, textTransform: 'none', fontSize: '0.75rem' }}>
              Suche ändern
            </Button>
          </Box>
        )}

        <ResultFilterBar
          filterSource={filterSource}
          onFilterChange={setFilterSource}
          sortBy={sortBy}
          onSortChange={setSortBy}
          showFutureAvailability={showFutureAvailability}
          onShowFutureAvailabilityChange={setShowFutureAvailability}
          showOwnProperties={showOwnProperties}
          onShowOwnPropertiesChange={setShowOwnProperties}
          isPropertyManager={isStaff}
        />

        {isLoading ? (
          <FeedSkeleton />
        ) : error ? (
          <ErrorState message={(error as Error).message} />
        ) : sorted.length === 0 ? (
          <FeedEmptyState filtered={filterSource !== 'ALL' || !showFutureAvailability || !showOwnProperties} />
        ) : (
          <>
            {futureCount > 0 && showFutureAvailability && (
              <Box sx={{
                mb: 2, px: 2, py: 1.375,
                bgcolor: '#faf5ff', border: '1px solid #e9d5ff', borderLeft: '3px solid #7c3aed',
                borderRadius: 1.5, display: 'flex', alignItems: 'flex-start', gap: 1.25,
              }}>
                <Zap size={15} color="#7c3aed" style={{ marginTop: 2, flexShrink: 0 }} />
                <Box>
                  <Typography sx={{ fontSize: '0.8rem', fontWeight: 700, color: '#5b21b6', mb: 0.2 }}>
                    {futureCount} Zukunftssignal{futureCount > 1 ? 'e' : ''} in diesen Ergebnissen
                  </Typography>
                  <Typography sx={{ fontSize: '0.75rem', color: '#6d28d9', lineHeight: 1.5 }}>
                    Noch nicht öffentlich verfügbare Flächen — gewonnen aus Mietvertrags-Auslaufzeiten, Bauprojekten und Marktbewegungen. Frühere Markttransparenz für Ihre Suche.
                  </Typography>
                </Box>
              </Box>
            )}
            <UnifiedResultFeed results={sorted} view={view} />
          </>
        )}
      </Box>
    </Box>
  )
}
