// React Imports
import { useEffect, useRef } from 'react'

// MUI Imports
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import Avatar from '@mui/material/Avatar'

// Third-party Imports
import classnames from 'classnames'
import PerfectScrollbar from 'react-perfect-scrollbar'

// Type Imports
import type { ChatMessage } from '@/types/apps/aiChatTypes'

// Component Imports
import CustomAvatar from '@core/components/mui/Avatar'
import ImagePreview from './ImagePreview'
import FilePreview from './FilePreview'

type Props = {
  messages: ChatMessage[]
  isBelowLgScreen?: boolean
}

const ChatMessages = ({ messages, isBelowLgScreen = false }: Props) => {
  // Refs
  const scrollRef = useRef<any>(null)

  // Scroll to bottom when new message is added
  useEffect(() => {
    if (scrollRef.current) {
      if (isBelowLgScreen) {
        // @ts-ignore
        scrollRef.current.scrollTop = scrollRef.current.scrollHeight
      } else {
        // @ts-ignore
        scrollRef.current._container.scrollTop = scrollRef.current._container.scrollHeight
      }
    }
  }, [messages, isBelowLgScreen])

  const formatTime = (date: Date | string) => {
    return new Date(date).toLocaleTimeString('fa-IR', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  if (messages.length === 0) {
    return (
      <Box className='flex flex-col items-center justify-center bs-full gap-4 text-center p-6'>
        <CustomAvatar variant='circular' size={80} color='primary' skin='light'>
          <i className='tabler-message-2 text-5xl' />
        </CustomAvatar>
        <Typography variant='h5' color='text.primary'>
          گفتگو را شروع کنید
        </Typography>
        <Typography variant='body2' color='text.secondary'>
          پیام خود را بنویسید یا تصویری ارسال کنید
        </Typography>
      </Box>
    )
  }

  const renderMessages = () => {
    return messages.map(message => {
      const isUser = message.role === 'user'

      return (
        <Box
          key={message.id}
          className={classnames('flex gap-4 p-4 md:p-6', {
            'flex-row-reverse': isUser,
            'bg-backgroundDefault': !isUser,
            'bg-backgroundPaper': isUser && ((message.images && message.images.length > 0) || (message.files && message.files.length > 0))
          })}
        >
          {!isUser ? (
            <Avatar
              sx={{
                width: 32,
                height: 32,
                backgroundColor: 'var(--mui-palette-primary-main)',
                color: 'var(--mui-palette-primary-contrastText)'
              }}
            >
              <i className='tabler-robot text-lg' />
            </Avatar>
          ) : (
            <CustomAvatar size={32} color='primary' skin='light'>
              <i className='tabler-user text-base' />
            </CustomAvatar>
          )}

          <Box
            className={classnames('flex flex-col gap-2', {
              'items-end': isUser,
              'items-start': !isUser,
              'max-is-[85%] md:max-is-[75%]': true
            })}
          >
            {/* Images */}
            {message.images && message.images.length > 0 && (
              <Box className='mb-2'>
                <ImagePreview images={message.images} readOnly />
              </Box>
            )}

            {/* Files */}
            {message.files && message.files.length > 0 && (
              <Box className='mb-2'>
                <FilePreview files={message.files} readOnly />
              </Box>
            )}

            {/* Text Content */}
            {message.content && (
              <Typography
                className={classnames('whitespace-pre-wrap pli-4 plb-2 rounded-lg shadow-xs', {
                  'bg-primary text-[var(--mui-palette-primary-contrastText)] rounded-tr-sm': isUser,
                  'bg-backgroundPaper text-textPrimary rounded-tl-sm': !isUser
                })}
                style={{ wordBreak: 'break-word' }}
              >
                {message.content}
              </Typography>
            )}

            {/* Timestamp */}
            <Typography variant='caption' color='text.disabled' className='text-xs'>
              {formatTime(message.timestamp)}
            </Typography>
          </Box>
        </Box>
      )
    })
  }

  if (isBelowLgScreen) {
    return (
      <Box
        ref={scrollRef}
        className='bs-full overflow-y-auto overflow-x-hidden flex flex-col'
        sx={{
          scrollBehavior: 'smooth'
        }}
      >
        {renderMessages()}
      </Box>
    )
  }

  return (
    <PerfectScrollbar ref={scrollRef} options={{ wheelPropagation: false }} className='bs-full'>
      <Box className='flex flex-col'>{renderMessages()}</Box>
    </PerfectScrollbar>
  )
}

export default ChatMessages

