import { useMemo } from 'react'
import { Box, CircularProgress, Typography } from '@mui/material'
import { Target } from 'lucide-react'
import { useProperties } from '../../hooks/useProperties'
import { ResultType } from '../../domain/enums'
import { useOfferWizardStore } from '../../stores/offerWizardStore'
import { deterministicMatchScore } from './latentNeedUtils'
import { SelectablePropertyMatchCard } from './SelectablePropertyMatchCard'
import { OfferCreationPanel } from './OfferCreationPanel'
import type { LatentNeed } from '../../domain/latentNeed'

interface OwnPropertyMatchListProps {
  need: LatentNeed
}

function buildReason(propertyAssetType: string, needAssetType: string, city: string, location: string): string {
  if (propertyAssetType === needAssetType) {
    const cityMatch = location.toLowerCase().includes(city.toLowerCase()) || city.toLowerCase().includes(location.toLowerCase())
    if (cityMatch) return 'Nutzungstyp und Standort passen sehr gut'
    return 'Passender Nutzungstyp, alternative Lage'
  }
  return 'Alternatives Profil — Detailprüfung empfohlen'
}

export function OwnPropertyMatchList({ need }: OwnPropertyMatchListProps) {
  const { data: properties = [], isLoading } = useProperties({ resultType: ResultType.VERIFIED_PORTFOLIO })

  const selectedIds = useOfferWizardStore(s => s.selectedPropertyIds)
  const toggle = useOfferWizardStore(s => s.toggleProperty)

  const scored = useMemo(() => {
    return properties
      .map(p => ({
        property: p,
        score: deterministicMatchScore(p.id, need.id),
        reason: buildReason(p.assetType, need.assetType, p.location.city, need.desiredLocation),
      }))
      .sort((a, b) => b.score - a.score)
  }, [properties, need])

  return (
    <Box
      sx={{
        width: 360,
        minWidth: 360,
        flexShrink: 0,
        borderLeft: '1px solid #e2e8f0',
        bgcolor: 'white',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
      }}
    >
      <Box
        sx={{
          px: 2,
          py: 1.25,
          borderBottom: '1px solid #e2e8f0',
          display: 'flex',
          alignItems: 'center',
          gap: 1,
          flexShrink: 0,
        }}
      >
        <Target size={14} color="#152642" />
        <Typography variant="body2" sx={{ fontWeight: 600, color: '#0f172a' }}>
          Eigene Objekte
        </Typography>
        <Box
          sx={{
            ml: 'auto',
            px: 1,
            py: 0.125,
            borderRadius: 1,
            bgcolor: '#152642',
            color: 'white',
            fontWeight: 600,
            fontSize: '0.7rem',
          }}
        >
          {scored.length}
        </Box>
      </Box>

      <Box sx={{ flex: 1, overflowY: 'auto', p: 1.25, display: 'flex', flexDirection: 'column', gap: 0.75 }}>
        {isLoading && (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
            <CircularProgress size={20} />
          </Box>
        )}
        {!isLoading && scored.length === 0 && (
          <Typography variant="caption" sx={{ color: '#64748b', fontSize: '0.8rem', textAlign: 'center', p: 2 }}>
            Keine Portfolio-Objekte vorhanden
          </Typography>
        )}
        {scored.map(({ property, score, reason }) => (
          <SelectablePropertyMatchCard
            key={property.id}
            property={property}
            matchScore={score}
            selected={selectedIds.includes(property.id)}
            onToggle={() => toggle(property.id)}
            reason={reason}
          />
        ))}
      </Box>

      <OfferCreationPanel
        selectedCount={selectedIds.length}
        needId={need.id}
        needTitle={need.title}
      />
    </Box>
  )
}
