import { useState } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { ChatMessageBubble } from '@/shared/ui/ChatMessageBubble'
import { OrderMessageBody } from '@/shared/ui/OrderMessageBody'
import { RichTextMessageEditor } from '@/shared/ui/RichTextMessageEditor'

type Message = {
  id: string
  authorType: 'user' | 'admin'
  text: string
  attachmentUrl?: string | null
  createdAt: string
}

type Props = {
  messages: Message[]
  isPending: boolean
  onSend: (text: string) => void
}

export function OrderChat({ messages, isPending, onSend }: Props) {
  const [text, setText] = useState('')
  const canSend = text.replace(/<[^>]*>/g, ' ').trim().length > 0

  const handleSend = () => {
    if (!canSend || isPending) return
    onSend(text.trim())
    setText('')
  }

  return (
    <Box sx={{ border: 1, borderColor: 'divider', borderRadius: 2, p: 2, bgcolor: 'background.paper' }}>
      <Typography variant="h6" gutterBottom>
        Чат по заказу
      </Typography>
      <Stack spacing={1} sx={{ mb: 2 }}>
        {messages.map((m) => (
          <ChatMessageBubble key={m.id} authorType={m.authorType === 'admin' ? 'admin' : 'user'}>
            <Typography variant="caption" color="text.secondary">
              {m.authorType === 'admin' ? 'Админ' : 'Вы'} · {new Date(m.createdAt).toLocaleString()}
            </Typography>
            <OrderMessageBody text={m.text} attachmentUrl={m.attachmentUrl} imageAlt="Чек или вложение" />
          </ChatMessageBubble>
        ))}
        {messages.length === 0 && <Typography color="text.secondary">Пока сообщений нет.</Typography>}
      </Stack>

      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ alignItems: { sm: 'flex-end' } }}>
        <Box sx={{ flexGrow: 1, width: '100%' }}>
          <RichTextMessageEditor value={text} onChange={setText} placeholder="Сообщение" />
        </Box>
        <Button variant="contained" onClick={handleSend} disabled={isPending || !canSend} sx={{ minWidth: 160 }}>
          Отправить
        </Button>
      </Stack>
    </Box>
  )
}
