import { useAppDispatch } from 'domains/store'
import { setLoadedImageEventIds } from 'domains/store/slice'
import { MessageImage } from 'domains/store/store.types'
import { useTranslatedEventData } from 'domains/translations/hooks'
import { FunctionalComponent } from 'preact'
import { useState } from 'preact/hooks'
import MessageContainer, {
  MessageContainerProps,
} from 'ui/components/conversation/message-container'
import ImageLightbox from './image-lightbox'

type ImageProps = {
  event: MessageImage
  descriptorId: string
} & Partial<MessageContainerProps>

const Image: FunctionalComponent<ImageProps> = ({
  event,
  descriptorId,
  ...props
}) => {
  const { body } = useTranslatedEventData(event)
  const [showLighbox, setShowLightbox] = useState(false)
  const dispatch = useAppDispatch()

  const handleOnLoad = () => {
    dispatch(setLoadedImageEventIds(event.payload.id))
    setShowLightbox(true)
  }

  return (
    <MessageContainer event={event} type="image" {...props}>
      <img
        src={body?.url}
        id={descriptorId}
        alt={body?.description || undefined}
        onLoad={handleOnLoad}
      />
      {body?.isZoomable && showLighbox && (
        <ImageLightbox description={body?.description} url={body?.url} />
      )}
    </MessageContainer>
  )
}

export default Image
