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 { useQuery } from '@tanstack/react-query'
import { useUnit } from 'effector-react'
import { fetchAdminAvatar } from '@/entities/user/api/user-api'
import { $user } from '@/shared/model/auth'
import { ChatMessageBubble } from '@/shared/ui/ChatMessageBubble'
import { OrderMessageBody } from '@/shared/ui/OrderMessageBody'
import { RichTextMessageEditor } from '@/shared/ui/RichTextMessageEditor.lazy'
import { UserAvatar } from '@/shared/ui/UserAvatar'

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 currentUser = useUnit($user)

  const adminAvatarQuery = useQuery({
    queryKey: ['admin', 'avatar'],
    queryFn: fetchAdminAvatar,
    staleTime: 5 * 60 * 1000,
  })

  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) => {
          const isAdminMsg = m.authorType === 'admin'
          const adminAv = adminAvatarQuery.data
          const avatarNode = isAdminMsg ? (
            <UserAvatar userId="admin" avatarUrl={adminAv?.avatar} avatarStyle={adminAv?.avatarStyle} size={24} />
          ) : currentUser ? (
            <UserAvatar
              userId={currentUser.id}
              avatarUrl={currentUser.avatar}
              avatarStyle={currentUser.avatarStyle}
              size={24}
            />
          ) : null
          return (
            <ChatMessageBubble key={m.id} authorType={isAdminMsg ? 'admin' : 'user'} avatar={avatarNode}>
              <Typography variant="caption" color="text.secondary">
                {isAdminMsg ? 'Админ' : 'Вы'} · {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>
  )
}
