import { useEffect, useState } from 'react'
import { Box, Button, CircularProgress, Typography } from '@mui/material'
import { ArrowRight, Building2, ClipboardList, MapPin, Ruler } from 'lucide-react'
import { useNavigate } from 'react-router'
import { useInquiryById, useMarkThreadAsRead } from '../../hooks/useInquiries'
import { usePropertyById } from '../../hooks/useProperties'
import { InquiryChat } from './InquiryChat'
import { RelatedPropertyCardPanel } from './RelatedPropertyCardPanel'
import type { Attachment } from '../../domain/inquiry'

interface InquiryDetailPanelProps {
  inquiryId: string
}

export function InquiryDetailPanel({ inquiryId }: InquiryDetailPanelProps) {
  const { data: inquiry, isLoading } = useInquiryById(inquiryId)
  const { data: property } = usePropertyById(inquiry?.propertyId ?? '')
  const markRead = useMarkThreadAsRead()
  const navigate = useNavigate()
  const [preparationOpen, setPreparationOpen] = useState(false)
  const [offerWizardOpen, setOfferWizardOpen] = useState(false)
  const [pendingAttachment, setPendingAttachment] = useState<Attachment | null>(null)

  useEffect(() => {
    if (inquiry && !inquiry.isRead) {
      markRead.mutate(inquiry.id)
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [inquiry?.id])

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress size={24} />
      </Box>
    )
  }

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

  const isLatentInquiry = !!inquiry.needId
  const propertyImage = property?.images?.[0]

  return (
    <>
      <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>

        {/* Header: tenant + subject + action */}
        <Box
          sx={{
            px: 2.5,
            py: 1.5,
            borderBottom: '1px solid #e2e8f0',
            bgcolor: 'white',
            display: 'flex',
            alignItems: 'center',
            gap: 2,
            flexShrink: 0,
          }}
        >
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Typography variant="caption" sx={{ color: '#64748b', fontSize: '0.75rem' }}>
              {inquiry.tenantName}
              {inquiry.tenantCompany ? ` · ${inquiry.tenantCompany}` : ''}
              {inquiry.tenantEmail ? ` · ${inquiry.tenantEmail}` : ''}
            </Typography>
            <Typography
              variant="body1"
              sx={{
                fontWeight: 600,
                color: '#0f172a',
                fontSize: '0.95rem',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}
            >
              {inquiry.subject}
            </Typography>
          </Box>
          {isLatentInquiry && (
            <Button
              size="small"
              variant="outlined"
              startIcon={<ClipboardList size={14} />}
              onClick={() => setPreparationOpen(true)}
              sx={{ textTransform: 'none', whiteSpace: 'nowrap', borderColor: '#152642', color: '#152642', '&:hover': { bgcolor: '#f0f4f8' } }}
            >
              Vorbereitung starten
            </Button>
          )}
        </Box>

        {/* Property context bar */}
        <Box
          sx={{
            px: 2,
            py: 1,
            borderBottom: '1px solid #e2e8f0',
            bgcolor: '#f8fafc',
            display: 'flex',
            alignItems: 'center',
            gap: 1.5,
            flexShrink: 0,
          }}
        >
          <Box
            sx={{
              width: 44,
              height: 44,
              borderRadius: 1,
              overflow: 'hidden',
              flexShrink: 0,
              bgcolor: '#e8e7e4',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            {propertyImage ? (
              <Box
                component="img"
                src={propertyImage}
                alt={property?.title}
                sx={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
              />
            ) : (
              <Building2 size={18} color="#94a3b8" />
            )}
          </Box>
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Typography
              sx={{ fontWeight: 600, color: '#0f172a', fontSize: '0.85rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: 1.3 }}
            >
              {property?.title ?? '—'}
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: '#64748b' }}>
              <MapPin size={11} style={{ flexShrink: 0 }} />
              <Typography variant="caption" sx={{ fontSize: '0.72rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {property?.location.city}
                {property?.areaSqm ? ` · ${property.areaSqm.toLocaleString('de-CH')} m²` : ''}
                {property?.rentPricePerSqm ? ` · CHF ${property.rentPricePerSqm}/m²/J.` : ''}
              </Typography>
            </Box>
          </Box>
          <Button
            size="small"
            endIcon={<ArrowRight size={12} />}
            onClick={() => navigate('/supply/properties')}
            sx={{ textTransform: 'none', fontSize: '0.75rem', color: '#152642', whiteSpace: 'nowrap', flexShrink: 0 }}
          >
            Objekt ansehen
          </Button>
        </Box>

        {/* Chat (flex: 1) */}
        <Box sx={{ flex: 1, overflow: 'hidden' }}>
          <InquiryChat
            inquiry={inquiry}
            onCreateOffer={() => setOfferWizardOpen(true)}
            pendingAttachment={pendingAttachment}
            onPendingAttachmentConsumed={() => setPendingAttachment(null)}
          />
        </Box>

        {/* Bottom: weitere passende Objekte */}
        <Box sx={{ flexShrink: 0, borderTop: '1px solid #e2e8f0' }}>
          <RelatedPropertyCardPanel
            propertyId={inquiry.propertyId}
            inquiryId={inquiry.id}
            compact
          />
        </Box>
      </Box>

      {preparationOpen && (
        <PreparationWizardLazy
          inquiryId={inquiry.id}
          inquiry={inquiry}
          onClose={() => setPreparationOpen(false)}
        />
      )}

      {offerWizardOpen && (
        <OfferCreationWizardLazy
          inquiryId={inquiry.id}
          propertyId={inquiry.propertyId}
          tenantName={inquiry.tenantName}
          onClose={() => setOfferWizardOpen(false)}
          onAttach={(label) => {
            setPendingAttachment({
              id: crypto.randomUUID(),
              fileName: label,
              fileType: 'application/pdf',
              generated: true,
            })
            setOfferWizardOpen(false)
          }}
        />
      )}
    </>
  )
}

// Lazy-loaded wizard wrappers to avoid circular imports at module load time
import { lazy, Suspense } from 'react'
const PreparationWizardComponent = lazy(() =>
  import('./PreparationWizard').then(m => ({ default: m.PreparationWizard }))
)
const OfferCreationWizardComponent = lazy(() =>
  import('./OfferCreationWizard').then(m => ({ default: m.OfferCreationWizard }))
)

import type { Inquiry } from '../../domain/inquiry'

function PreparationWizardLazy(props: { inquiryId: string; inquiry: Inquiry; onClose: () => void }) {
  return (
    <Suspense fallback={null}>
      <PreparationWizardComponent {...props} />
    </Suspense>
  )
}

function OfferCreationWizardLazy(props: {
  inquiryId: string
  propertyId: string
  tenantName: string
  onClose: () => void
  onAttach: (label: string) => void
}) {
  return (
    <Suspense fallback={null}>
      <OfferCreationWizardComponent {...props} />
    </Suspense>
  )
}
