import { Box, Chip, Typography } from '@mui/material'
import { useProperties } from '../../hooks/useProperties'
import { useMatchCenterStore } from '../../stores/matchCenterStore'
import { MatchCenterSkeleton } from './MatchCenterSkeleton'
import type { Match } from '../../domain/match'

interface Props { matches: Match[] }

export function PropertySelectionPanel({ matches }: Props) {
  const { data: properties = [], isLoading } = useProperties()
  const { selectedPropertyId, setSelectedProperty } = useMatchCenterStore()

  if (isLoading) return <MatchCenterSkeleton />

  return (
    <Box sx={{ overflowY: 'auto', flex: 1 }}>
      {properties.map(prop => {
        const pendingCount = matches.filter(m => m.propertyId === prop.id && m.status === 'PENDING_REVIEW').length
        const isSelected = selectedPropertyId === prop.id
        return (
          <Box
            key={prop.id}
            onClick={() => setSelectedProperty(isSelected ? null : prop.id)}
            sx={{
              p: 1.5,
              cursor: 'pointer',
              borderBottom: '1px solid #f1f5f9',
              borderLeft: isSelected ? '3px solid #1e3a5f' : '3px solid transparent',
              bgcolor: isSelected ? '#eff6ff' : 'transparent',
              '&:hover': { bgcolor: isSelected ? '#eff6ff' : '#f8fafc' },
            }}
          >
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 0.5 }}>
              <Typography variant="body2" sx={{ fontWeight: 600, lineHeight: 1.3, flex: 1, mr: 0.5 }}>
                {prop.title}
              </Typography>
              {pendingCount > 0 && (
                <Chip label={pendingCount} size="small"
                  sx={{ bgcolor: '#d97706', color: 'white', fontSize: 10, height: 18, minWidth: 22 }} />
              )}
            </Box>
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
              {prop.location.city} · {prop.areaSqm} m²
            </Typography>
            <Chip label={prop.assetType} size="small" sx={{ mt: 0.5, fontSize: 10, height: 18 }} />
          </Box>
        )
      })}
    </Box>
  )
}
