import { Box, Button, Card, CardContent, Chip, LinearProgress, Typography } from '@mui/material'
import type { Property } from '../../domain/property'
import { FreshnessStatus } from '../../domain/enums'
import {
  getAssetTypeColor,
  getAssetTypeLabel,
  getAvailabilityChipColor,
  getAvailabilityLabel,
  getResultTypeColor,
  getResultTypeLabel,
  qualityColor,
} from './propertyHelpers'

export interface PropertyCardProps {
  property: Property
  matchScore?: number
  positiveFactors?: string[]
  topTradeoff?: string
  selected?: boolean
  onSelect?: () => void
  onViewDetail?: () => void
  onSaveToShortlist?: () => void
  onFindMatches?: () => void
}

const STALE_STATUSES: FreshnessStatus[] = [FreshnessStatus.STALE, FreshnessStatus.OUTDATED]

export function PropertyCard({
  property: p,
  matchScore,
  positiveFactors,
  topTradeoff,
  selected,
  onSelect,
  onViewDetail,
  onSaveToShortlist,
  onFindMatches,
}: PropertyCardProps) {
  const isStale = STALE_STATUSES.includes(p.dataQuality.freshness)
  const isLowConfidence = p.confidenceScore < 0.65

  const borderLeft = selected ? '4px solid #1e3a5f' : '4px solid transparent'

  return (
    <Card
      onClick={onSelect}
      sx={{
        borderLeft,
        borderTop: isStale ? '2px solid #d97706' : undefined,
        bgcolor: isLowConfidence ? 'rgba(251,191,36,0.04)' : 'inherit',
        cursor: onSelect ? 'pointer' : 'default',
        mb: 1.5,
        transition: 'box-shadow 0.15s ease',
        '&:hover': onSelect ? { boxShadow: 3 } : {},
      }}
    >
      <CardContent sx={{ p: 2, '&:last-child': { pb: 1.5 } }}>
        {/* Header Zone */}
        <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mb: 1 }}>
          <Chip label={getAssetTypeLabel(p.assetType)} size="small" sx={{ bgcolor: getAssetTypeColor(p.assetType), color: 'white', fontSize: '0.68rem' }} />
          <Chip label={getResultTypeLabel(p.resultType)} size="small" sx={{ bgcolor: getResultTypeColor(p.resultType), color: 'white', fontSize: '0.68rem' }} />
          <Chip label={getAvailabilityLabel(p.availabilityStatus)} size="small" color={getAvailabilityChipColor(p.availabilityStatus)} variant="outlined" />
          {isStale && <Chip label="Veraltete Daten" size="small" color="warning" variant="outlined" />}
          {isLowConfidence && <Chip label="Niedrige Konfidenz" size="small" color="warning" variant="outlined" />}
        </Box>

        {/* Primary Zone */}
        <Typography variant="subtitle2" sx={{ fontWeight: 600, lineHeight: 1.3, mb: 0.25 }}>
          {p.title}
        </Typography>
        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mb: 0.75 }}>
          {p.address.street} {p.address.houseNumber}, {p.address.city}
          {p.location.canton ? ` · ${p.location.canton}` : ''}
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, mb: 1 }}>
          <Box>
            <Typography variant="caption" color="text.secondary">Fläche</Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>{p.areaSqm.toLocaleString('de-CH')} m²</Typography>
          </Box>
          <Box>
            <Typography variant="caption" color="text.secondary">Miete/m²/Jahr</Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>
              {p.rentPricePerSqm > 0 ? `CHF ${p.rentPricePerSqm}` : <Typography component="span" variant="body2" color="text.disabled">k.A.</Typography>}
            </Typography>
          </Box>
          <Box>
            <Typography variant="caption" color="text.secondary">Verfügbar ab</Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>
              {p.availabilityDate ? new Date(p.availabilityDate).toLocaleDateString('de-CH') : '–'}
            </Typography>
          </Box>
        </Box>

        {/* Matchability Zone */}
        {matchScore !== undefined ? (
          <Box sx={{ p: 1, bgcolor: 'rgba(30,58,95,0.05)', borderRadius: 1, mb: 1 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
              <Chip
                label={`Match ${matchScore}`}
                size="small"
                sx={{ fontWeight: 700, bgcolor: matchScore >= 80 ? '#1a7a4a' : matchScore >= 60 ? '#d97706' : '#c0392b', color: 'white' }}
              />
            </Box>
            {positiveFactors && positiveFactors.length > 0 && (
              <Box sx={{ mb: 0.5 }}>
                {positiveFactors.slice(0, 3).map((f, i) => (
                  <Typography key={i} variant="caption" sx={{ display: 'block', color: '#1a7a4a' }}>✓ {f}</Typography>
                ))}
              </Box>
            )}
            {topTradeoff && (
              <Typography variant="caption" sx={{ color: '#d97706' }}>⚠ {topTradeoff}</Typography>
            )}
          </Box>
        ) : (
          <Box sx={{ p: 1, bgcolor: 'rgba(0,0,0,0.03)', borderRadius: 1, mb: 1 }}>
            <Typography variant="caption" color="text.disabled">
              Bedarfsprofil wählen für Matchbarkeit
            </Typography>
          </Box>
        )}

        {/* Data Quality Zone */}
        <Box sx={{ mb: 1 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.25 }}>
            <Typography variant="caption" color="text.secondary">Datenqualität</Typography>
            <Typography variant="caption" sx={{ fontWeight: 600 }}>{Math.round(p.dataQuality.score * 100)}%</Typography>
          </Box>
          <LinearProgress variant="determinate" value={p.dataQuality.score * 100} color={qualityColor(p.dataQuality.score)} sx={{ height: 4, borderRadius: 2, mb: 0.5 }} />
          {p.dataQuality.missingCriticalFields.length > 0 && (
            <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
              {p.dataQuality.missingCriticalFields.slice(0, 3).map(f => (
                <Chip key={f} label={f} size="small" color="warning" variant="outlined" sx={{ fontSize: '0.65rem', height: 18 }} />
              ))}
              {p.dataQuality.missingCriticalFields.length > 3 && (
                <Typography variant="caption" color="warning.main">+{p.dataQuality.missingCriticalFields.length - 3} mehr</Typography>
              )}
            </Box>
          )}
        </Box>

        {/* Action Zone */}
        <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap' }} onClick={e => e.stopPropagation()}>
          <Button size="small" variant="contained" sx={{ textTransform: 'none', fontSize: '0.75rem', py: 0.25 }} onClick={onViewDetail}>Details</Button>
          <Button size="small" variant="outlined" sx={{ textTransform: 'none', fontSize: '0.75rem', py: 0.25 }} onClick={onSaveToShortlist}>Shortlist</Button>
          <Button size="small" variant="outlined" sx={{ textTransform: 'none', fontSize: '0.75rem', py: 0.25 }} onClick={onFindMatches}>Matches finden</Button>
        </Box>
      </CardContent>
    </Card>
  )
}
