import { useEffect, useRef } from 'react'
import { Box, Button } from '@mui/material'
import { FileText } from 'lucide-react'
import type { Inquiry, Attachment } from '../../domain/inquiry'
import { InquiryMessageBubble } from './InquiryMessageBubble'
import { InquiryReplyComposer } from './InquiryReplyComposer'

interface InquiryChatProps {
  inquiry: Inquiry
  onCreateOffer?: () => void
  pendingAttachment?: Attachment | null
  onPendingAttachmentConsumed?: () => void
}

export function InquiryChat({
  inquiry,
  onCreateOffer,
  pendingAttachment,
  onPendingAttachmentConsumed,
}: InquiryChatProps) {
  const endRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' })
  }, [inquiry.thread.length])

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', flex: 1, overflow: 'hidden' }}>
      <Box sx={{ overflowY: 'auto', flex: 1, p: 2, bgcolor: 'white' }}>
        {inquiry.thread.map((m, idx) => (
          <Box key={m.id}>
            <InquiryMessageBubble message={m} />
            {idx === 0 && m.senderType === 'tenant' && onCreateOffer && (
              <Box sx={{ display: 'flex', justifyContent: 'flex-start', mb: 1.5, ml: 0.5 }}>
                <Button
                  size="small"
                  variant="outlined"
                  startIcon={<FileText size={13} />}
                  onClick={onCreateOffer}
                  sx={{
                    textTransform: 'none',
                    fontSize: '0.75rem',
                    borderColor: '#cbd5e1',
                    color: '#475569',
                    '&:hover': { borderColor: '#152642', color: '#152642', bgcolor: '#f0f4f8' },
                  }}
                >
                  Angebot erstellen
                </Button>
              </Box>
            )}
          </Box>
        ))}
        <div ref={endRef} />
      </Box>
      <InquiryReplyComposer
        inquiryId={inquiry.id}
        defaultSubject={inquiry.subject}
        tenantName={inquiry.tenantName}
        pendingAttachment={pendingAttachment}
        onPendingAttachmentConsumed={onPendingAttachmentConsumed}
      />
    </Box>
  )
}
