import { useNavigate, useParams, useSearchParams } from 'react-router'
import {
  Box,
  Button,
  CircularProgress,
  Divider,
  Paper,
  Typography,
} from '@mui/material'
import { ArrowLeft, Building2, MapPin, ShieldCheck } from 'lucide-react'
import { usePropertyById } from '../../hooks/useProperties'
import { ASSET_LABELS } from '../../components/match-detail/MatchDetailPropertyDetails'
import { PropertyDetailPublicSections } from '../../components/match-detail/PropertyDetailPublicSections'
import { PropertyContactForm } from '../../components/demand/PropertyContactForm'

// ── Page ──────────────────────────────────────────────────────────────────────

export default function PropertyDetail() {
  const { propertyId } = useParams<{ propertyId: string }>()
  const [searchParams] = useSearchParams()
  const highlightUnitId = searchParams.get('unit')
  const navigate = useNavigate()

  const { data: property, isLoading } = usePropertyById(propertyId ?? '')

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', pt: 8 }}>
        <CircularProgress />
      </Box>
    )
  }

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

  const preMarketUnits = (property.units ?? []).filter(u => u.schattenmarktRelease?.enabled)
  const monthlyPerSqm = Math.round(property.rentPricePerSqm / 12)

  return (
    <Box sx={{ maxWidth: 860, mx: 'auto', p: { xs: 2, md: 3 } }}>

      {/* ── Back ── */}
      <Button
        startIcon={<ArrowLeft size={15} />}
        onClick={() => navigate(-1)}
        size="small"
        sx={{ mb: 2, textTransform: 'none', color: 'text.secondary' }}
      >
        Zurück zu den Ergebnissen
      </Button>

      {/* ── Header ── */}
      <Paper sx={{ mb: 2, overflow: 'hidden' }}>
        {property.images?.[0] && (
          <Box
            component="img"
            src={property.images[0]}
            alt={property.title}
            sx={{ width: '100%', height: 220, objectFit: 'cover' }}
          />
        )}
        <Box sx={{ p: 2.5 }}>
          <Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 1 }}>
            <Box>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mb: 0.5 }}>
                <Building2 size={15} color="#7c3aed" />
                <Typography variant="caption" sx={{ color: '#7c3aed', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                  {ASSET_LABELS[property.assetType] ?? property.assetType}
                </Typography>
              </Box>
              <Typography variant="h5" sx={{ fontWeight: 700, mb: 0.5 }}>{property.title}</Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                <MapPin size={13} color="#64748b" />
                <Typography variant="body2" color="text.secondary">
                  {property.address.street} {property.address.houseNumber}, {property.address.postalCode} {property.address.city}
                </Typography>
              </Box>
            </Box>
            <Box sx={{ textAlign: 'right' }}>
              <Typography variant="h6" sx={{ fontWeight: 700, color: '#152642' }}>
                CHF {monthlyPerSqm.toLocaleString('de-CH')}/m²/Mt.
              </Typography>
              <Typography variant="caption" color="text.secondary">{property.areaSqm.toLocaleString('de-CH')} m² total</Typography>
            </Box>
          </Box>

          {preMarketUnits.length > 0 && (
            <Box sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1, bgcolor: '#faf5ff', border: '1px solid #e9d5ff', borderRadius: 1, px: 1.5, py: 1 }}>
              <ShieldCheck size={14} color="#7c3aed" />
              <Typography sx={{ fontSize: '0.82rem', color: '#4c1d95', fontWeight: 600 }}>
                {preMarketUnits.length} Einheit{preMarketUnits.length !== 1 ? 'en' : ''} für Pre-Market freigegeben — noch vor offizieller Insertion
              </Typography>
            </Box>
          )}
        </Box>
      </Paper>

      <PropertyDetailPublicSections property={property} highlightUnitId={highlightUnitId} />

      <PropertyContactForm
        propertyTitle={property.title}
        highlightUnitId={highlightUnitId}
        units={property.units}
      />

      <Divider sx={{ my: 2 }} />
      <Typography variant="caption" color="text.secondary" sx={{ display: 'block', lineHeight: 1.5 }}>
        Diese Fläche ist noch nicht offiziell auf dem Markt. Die Verwaltung hat sie explizit für qualifizierte Suchanfragen freigegeben. Ihre Anfrage wird vertraulich behandelt.
      </Typography>
    </Box>
  )
}
