import { useEffect, useState } from 'react'
import { Box, Button, CircularProgress, Typography } from '@mui/material'
import { ClipboardList } from 'lucide-react'
import { useInquiryById, useMarkThreadAsRead } from '../../hooks/useInquiries'
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 markRead = useMarkThreadAsRead()
  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

  return (
    <>
      <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
        <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: '#1e3a5f', color: '#1e3a5f', '&:hover': { bgcolor: '#f0f4f8' } }}
            >
              Vorbereitung starten
            </Button>
          )}
        </Box>

        <Box sx={{ flex: 1, display: 'flex', flexDirection: { xs: 'column', md: 'row' }, overflow: 'hidden' }}>
          <InquiryChat
            inquiry={inquiry}
            onCreateOffer={() => setOfferWizardOpen(true)}
            pendingAttachment={pendingAttachment}
            onPendingAttachmentConsumed={() => setPendingAttachment(null)}
          />
          <Box sx={{ width: { xs: '100%', md: 300 }, flexShrink: 0, borderTop: { xs: '1px solid #e2e8f0', md: 'none' }, maxHeight: { xs: 280, md: 'none' }, overflowY: 'auto' }}>
            <RelatedPropertyCardPanel
              propertyId={inquiry.propertyId}
              inquiryId={inquiry.id}
            />
          </Box>
        </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>
  )
}
