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

interface RelatedPropertyCardPanelProps {
  propertyId: string
  inquiryId: string
}

export function RelatedPropertyCardPanel({ propertyId, inquiryId }: RelatedPropertyCardPanelProps) {
  const { data: property, isLoading } = usePropertyById(propertyId)
  const navigate = useNavigate()
  const [additionalMatches, setAdditionalMatches] = useState<AdditionalPropertyMatch[]>([])
  const [loadingMatches, setLoadingMatches] = useState(false)

  useEffect(() => {
    setLoadingMatches(true)
    matchService
      .getAdditionalMatchesForInquiry(inquiryId, { minScore: 80, excludePropertyId: propertyId })
      .then(setAdditionalMatches)
      .finally(() => setLoadingMatches(false))
  }, [inquiryId, propertyId])

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', p: 4 }}>
        <CircularProgress size={20} />
      </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',
      }}
    >
      <Typography variant="caption" sx={{ color: '#64748b', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>
        Bezogenes Objekt
      </Typography>

      <Box
        sx={{
          height: 140,
          borderRadius: 1.5,
          overflow: 'hidden',
          bgcolor: '#e2e8f0',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundImage: image ? `url(${image})` : 'none',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      >
        {!image && <Building2 size={32} color="#94a3b8" />}
      </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', fontSize: '0.8125rem' }}>
          <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', fontSize: '0.8125rem' }}>
          <Ruler size={14} />
          <Typography variant="body2" sx={{ fontSize: '0.8125rem' }}>
            {property.areaSqm.toLocaleString('de-CH')} m² · CHF {property.rentPricePerSqm}/m²
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: '#475569', fontSize: '0.8125rem' }}>
          <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>

      {/* Weitere Matches */}
      <Divider sx={{ my: 0.5 }} />
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
        <Trophy size={14} color="#d97706" />
        <Typography variant="caption" sx={{ color: '#64748b', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, fontSize: '0.68rem' }}>
          Weitere passende Objekte
        </Typography>
      </Box>

      {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 AdditionalMatchCard({ match }: { match: AdditionalPropertyMatch }) {
  const navigate = useNavigate()
  return (
    <Box
      sx={{
        border: '1px solid #e2e8f0',
        borderRadius: 1.5,
        overflow: 'hidden',
        bgcolor: 'white',
      }}
    >
      {match.imageUrl && (
        <Box
          sx={{
            height: 70,
            backgroundImage: `url(${match.imageUrl})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
          }}
        />
      )}
      <Box sx={{ p: 1 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 0.5 }}>
          <Typography variant="caption" sx={{ fontWeight: 600, color: '#0f172a', fontSize: '0.75rem', lineHeight: 1.3 }}>
            {match.title}
          </Typography>
          <Box
            sx={{
              px: 0.75,
              py: 0.125,
              borderRadius: 1,
              bgcolor: match.matchScore >= 90 ? '#fef3c7' : '#e0e7ff',
              color: match.matchScore >= 90 ? '#92400e' : '#3730a3',
              fontWeight: 700,
              fontSize: '0.65rem',
              flexShrink: 0,
              ml: 0.5,
            }}
          >
            {match.matchScore}%
          </Box>
        </Box>
        <Typography variant="caption" sx={{ color: '#64748b', fontSize: '0.7rem', display: 'block', mb: 0.5 }}>
          {match.location} · {match.areaSqm.toLocaleString('de-CH')} m² · CHF {match.rentPricePerSqm}/m²
        </Typography>
        {match.reasons.length > 0 && (
          <Box sx={{ mb: 0.5 }}>
            {match.reasons.map((r, i) => (
              <Typography key={i} variant="caption" sx={{ color: '#15803d', fontSize: '0.68rem', display: 'block', lineHeight: 1.4 }}>
                + {r}
              </Typography>
            ))}
          </Box>
        )}
        {match.topUncertainty && (
          <Typography variant="caption" sx={{ color: '#92400e', fontSize: '0.68rem', display: 'block', lineHeight: 1.4, mb: 0.25 }}>
            ⚠ {match.topUncertainty}
          </Typography>
        )}
        <Button
          size="small"
          endIcon={<ArrowRight size={11} />}
          onClick={() => navigate('/supply/properties')}
          sx={{ textTransform: 'none', fontSize: '0.7rem', mt: 0.5, p: 0, minWidth: 0, color: '#1e3a5f' }}
        >
          Ansehen
        </Button>
      </Box>
    </Box>
  )
}
