import { Box, Button, CircularProgress, Divider, Typography } from '@mui/material'
import { ArrowRight, Building2, Calendar, MapPin, Ruler } from 'lucide-react'
import { useNavigate } from 'react-router'
import { usePropertyById } from '../../hooks/useProperties'
import { useAdditionalMatchesForInquiry } from '../../hooks/useMatches'
import type { AdditionalPropertyMatch } from '../../domain/additionalMatch'

interface RelatedPropertyCardPanelProps {
  propertyId: string
  inquiryId: string
  compact?: boolean
}

export function RelatedPropertyCardPanel({ propertyId, inquiryId, compact }: RelatedPropertyCardPanelProps) {
  const { data: property, isLoading } = usePropertyById(propertyId)
  const navigate = useNavigate()
  const {
    data: additionalMatches = [],
    isLoading: loadingMatches,
  } = useAdditionalMatchesForInquiry(inquiryId, { minScore: 80, excludePropertyId: propertyId })

  if (isLoading && !compact) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', p: 4 }}>
        <CircularProgress size={20} />
      </Box>
    )
  }

  if (compact) {
    return (
      <Box sx={{ px: 1.5, pt: 1.25, pb: 1.5, bgcolor: 'white' }}>
        <Typography
          variant="caption"
          sx={{ color: '#64748b', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, fontSize: '0.65rem', display: 'block', mb: 1 }}
        >
          Weitere passende Objekte
        </Typography>

        {loadingMatches ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 1.5 }}>
            <CircularProgress size={16} />
          </Box>
        ) : additionalMatches.length === 0 ? (
          <Typography variant="caption" sx={{ color: '#94a3b8', fontSize: '0.72rem' }}>
            Keine weiteren Matches
          </Typography>
        ) : (
          <Box
            sx={{
              display: 'flex',
              gap: 1.25,
              overflowX: 'auto',
              pb: 0.5,
              '&::-webkit-scrollbar': { height: 3 },
              '&::-webkit-scrollbar-thumb': { bgcolor: '#cbd5e1', borderRadius: 2 },
            }}
          >
            {additionalMatches.map(m => (
              <MatchSliderCard key={m.propertyId} match={m} />
            ))}
          </Box>
        )}
      </Box>
    )
  }

  if (!property) {
    return (
      <Box sx={{ p: 2 }}>
        <Typography variant="body2" color="text.secondary">
          Objekt nicht gefunden
        </Typography>
      </Box>
    )
  }

  const image = property.images?.[0]

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        gap: 1.5,
        p: 2,
        borderLeft: '1px solid #e2e8f0',
        bgcolor: '#f8fafc',
        height: '100%',
        overflowY: 'auto',
      }}
    >
      <Box
        sx={{
          aspectRatio: '3/2',
          borderRadius: 1.5,
          overflow: 'hidden',
          bgcolor: '#f4f3f0',
        }}
      >
        {image ? (
          <Box component="img" src={image} alt={property.title}
            sx={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        ) : (
          <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Building2 size={32} color="#94a3b8" />
          </Box>
        )}
      </Box>

      <Typography variant="body1" sx={{ fontWeight: 600, color: '#0f172a', fontSize: '0.95rem' }}>
        {property.title}
      </Typography>

      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: '#475569' }}>
          <MapPin size={14} />
          <Typography variant="body2" sx={{ fontSize: '0.8125rem' }}>
            {property.location.city}
            {property.location.district ? `, ${property.location.district}` : ''}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: '#475569' }}>
          <Ruler size={14} />
          <Typography variant="body2" sx={{ fontSize: '0.8125rem' }}>
            {property.areaSqm.toLocaleString('de-CH')} m² · CHF {property.rentPricePerSqm}/m²/Jahr
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: '#475569' }}>
          <Calendar size={14} />
          <Typography variant="body2" sx={{ fontSize: '0.8125rem' }}>
            Verfügbar ab {new Date(property.availabilityDate).toLocaleDateString('de-CH')}
          </Typography>
        </Box>
      </Box>

      {property.description && (
        <Typography variant="body2" sx={{ color: '#64748b', fontSize: '0.8125rem', lineHeight: 1.5 }}>
          {property.description}
        </Typography>
      )}

      <Button
        variant="outlined"
        size="small"
        endIcon={<ArrowRight size={14} />}
        onClick={() => navigate('/supply/properties')}
        sx={{ textTransform: 'none' }}
      >
        Objekt ansehen
      </Button>

      <Divider sx={{ my: 0.5 }} />
      <Typography variant="caption" sx={{ color: '#64748b', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, fontSize: '0.68rem' }}>
        Weitere passende Objekte
      </Typography>

      {loadingMatches ? (
        <CircularProgress size={16} sx={{ alignSelf: 'center' }} />
      ) : additionalMatches.length === 0 ? (
        <Typography variant="caption" sx={{ color: '#94a3b8', fontSize: '0.75rem' }}>
          Keine weiteren Matches
        </Typography>
      ) : (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
          {additionalMatches.map(m => (
            <AdditionalMatchCard key={m.propertyId} match={m} />
          ))}
        </Box>
      )}
    </Box>
  )
}

function MatchSliderCard({ match }: { match: AdditionalPropertyMatch }) {
  const navigate = useNavigate()
  return (
    <Box
      onClick={() => navigate('/supply/properties')}
      sx={{
        flexShrink: 0,
        width: 168,
        border: '1px solid #e8e7e4',
        borderRadius: 1.5,
        overflow: 'hidden',
        cursor: 'pointer',
        bgcolor: 'white',
        transition: 'border-color 0.15s, box-shadow 0.15s',
        '&:hover': {
          borderColor: '#b0aead',
          boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
        },
      }}
    >
      {/* Image — 16:9 crop, compact supplementary card */}
      <Box sx={{ position: 'relative', height: 60, bgcolor: '#f4f3f0', overflow: 'hidden' }}>
        {match.imageUrl ? (
          <Box
            component="img"
            src={match.imageUrl}
            alt={match.title}
            sx={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          />
        ) : (
          <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Building2 size={16} color="#94a3b8" />
          </Box>
        )}
        {/* Score badge overlay */}
        <Box
          sx={{
            position: 'absolute',
            top: 6,
            right: 6,
            bgcolor: 'rgba(15,23,42,0.72)',
            color: 'white',
            fontSize: '0.7rem',
            fontWeight: 700,
            px: 0.75,
            py: 0.25,
            borderRadius: '4px',
            lineHeight: 1.4,
          }}
        >
          {match.matchScore}%
        </Box>
      </Box>
      <Box sx={{ p: 0.75 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', mb: 0.2 }}>
          <Typography
            sx={{ fontWeight: 600, color: '#0f172a', fontSize: '0.75rem', lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, mr: 0.5 }}
          >
            {match.title}
          </Typography>
          <Typography sx={{ fontSize: '0.7rem', fontWeight: 700, color: '#152642', flexShrink: 0 }}>
            {match.matchScore}%
          </Typography>
        </Box>
        <Typography variant="caption" sx={{ color: '#64748b', fontSize: '0.68rem', display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {match.location}
        </Typography>
        {match.reasons[0] && (
          <Typography variant="caption" sx={{ color: '#15803d', fontSize: '0.67rem', display: 'block', lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', mt: 0.2 }}>
            + {match.reasons[0]}
          </Typography>
        )}
      </Box>
    </Box>
  )
}

function AdditionalMatchCard({ match }: { match: AdditionalPropertyMatch }) {
  const navigate = useNavigate()
  return (
    <Box
      sx={{
        borderTop: '1px solid #f1f5f9',
        pt: 1,
        '&:first-of-type': { borderTop: 'none', pt: 0 },
      }}
    >
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', mb: 0.25 }}>
        <Typography sx={{ fontWeight: 600, color: '#0f172a', fontSize: '0.8rem', lineHeight: 1.3, mr: 0.5 }}>
          {match.title}
        </Typography>
        <Typography sx={{ fontSize: '0.75rem', fontWeight: 700, color: '#152642', flexShrink: 0 }}>
          {match.matchScore}%
        </Typography>
      </Box>
      <Typography variant="caption" sx={{ color: '#64748b', fontSize: '0.72rem', display: 'block', mb: 0.375 }}>
        {match.location} · {match.areaSqm.toLocaleString('de-CH')} m²
      </Typography>
      {match.reasons[0] && (
        <Typography variant="caption" sx={{ color: '#15803d', fontSize: '0.7rem', display: 'block', mb: 0.375, lineHeight: 1.4 }}>
          + {match.reasons[0]}
        </Typography>
      )}
      <Button
        size="small"
        endIcon={<ArrowRight size={10} />}
        onClick={() => navigate('/supply/properties')}
        sx={{ textTransform: 'none', fontSize: '0.7rem', p: 0, minWidth: 0, color: '#152642' }}
      >
        Ansehen
      </Button>
    </Box>
  )
}
