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

interface Props { matches: Match[] }

export function NeedSelectionPanel({ matches }: Props) {
  const { data: needs = [], isLoading } = useNeeds()
  const { selectedNeedId, setSelectedNeed } = useMatchCenterStore()

  if (isLoading) return <MatchCenterSkeleton />

  return (
    <Box sx={{ overflowY: 'auto', flex: 1 }}>
      {needs.map((need: Need) => {
        const pendingCount = matches.filter(m => m.needId === need.id && m.status === 'PENDING_REVIEW').length
        const isSelected = selectedNeedId === need.id
        return (
          <Box
            key={need.id}
            onClick={() => setSelectedNeed(isSelected ? null : need.id)}
            sx={{
              p: 1.5,
              cursor: 'pointer',
              borderBottom: '1px solid #f1f5f9',
              borderRight: isSelected ? '3px solid #d97706' : '3px solid transparent',
              bgcolor: isSelected ? '#fef3c7' : 'transparent',
              '&:hover': { bgcolor: isSelected ? '#fef3c7' : '#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 }}>
                {need.companyName}
              </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' }}>
              {need.requiredArea.min}–{need.requiredArea.max} m² · {need.preferredLocations.slice(0, 2).join(', ')}
            </Typography>
            <Chip label={need.assetType} size="small" sx={{ mt: 0.5, fontSize: 10, height: 18 }} />
          </Box>
        )
      })}
    </Box>
  )
}
