import { FileType } from "@openchat/types"
import { Image, NativeScrollEvent, ScrollView, View } from "react-native"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { useEffect, useRef, useState } from "react"
import { Icon } from "../../../ui-components/icon/icon.component"
import { AppControllers } from "../../../app/app-context"
import { useStyles } from "./message-room-assets-media.style"
import { SafeAreaView } from "react-native-safe-area-context"
import { EmptyState } from "../../../ui-components/empty-state/empty-state.component"
import { AppAssets } from "../../../app/app-assets"

export const MessageRoomAssetsMedia = ({
  roomId,
  onClose,
}: {
  roomId: string
  onClose: () => void
}) => {
  const [media, setMedia] = useState<FileType[]>([])
  const [skip, setSkip] = useState(0)
  const [isFetching, setFetching] = useState(false)
  const mediaSize = useRef(0)
  const styles = useStyles()

  // ---------------------------------------------------------------------------
  // effects
  // ---------------------------------------------------------------------------

  useEffect(() => {
    loadAssets(0)
  }, [roomId])

  useEffect(() => {
    loadAssets(skip)
  }, [skip])

  // ---------------------------------------------------------------------------
  // functions
  // ---------------------------------------------------------------------------

  async function scrollHandler({
    layoutMeasurement,
    contentOffset,
    contentSize,
  }: NativeScrollEvent) {
    if (isFetching) return
    const paddingToBottom = 200
    if (
      layoutMeasurement.height + contentOffset.y >=
      contentSize.height - paddingToBottom
    )
      setSkip((prevState) => prevState + 30)
  }

  async function loadAssets(skip: number) {
    setFetching(true)

    const attachments = await AppControllers.attachment.getByRoomId({
      roomId: roomId,
      skip: skip,
      type: "media",
    })

    const media = await AppControllers.file.getByRoomId({
      roomId: roomId,
      ids: attachments
        .map((attachment) => attachment.fileId)
        .filter((fileId) => fileId !== null) as string[],
      skip: skip,
    })
    // const media = await LocalData.attachmxent.fetch({
    //   type: "media",
    //   roomId: room.id,
    //   skip: skip,
    // })

    if (skip === 0) {
      setSkip(0)
      setMedia(media)
    } else {
      setMedia((prev) => [...prev, ...media])
    }

    setFetching(false)
  }

  return (
    <SafeAreaView style={styles.wrapper} edges={["top"]}>
      {/* --------------------------------------------------------------------------- */}
      {/* HEADER */}
      {/* --------------------------------------------------------------------------- */}

      <View style={styles.headerWrapper}>
        <Icon
          onPress={onClose}
          name={"far fa-arrow-left"}
          size={18}
          fill={"#8592AA"}
        />
        <StyledText style={styles.headerText}>Images and videos</StyledText>
      </View>
      <ScrollView
        onScroll={({ nativeEvent }) => {
          scrollHandler(nativeEvent)
        }}
      >
        {/* --------------------------------------------------------------------------- */}
        {/* MEDIA FILE  */}
        {/* --------------------------------------------------------------------------- */}
        <View
          style={styles.imageWrapper}
          onLayout={(event) => {
            const { width } = event.nativeEvent.layout
            mediaSize.current = (width + 2) / 3 - 2
          }}
        >
          {media.map((media) => (
            <>
              {media.mimeType.startsWith("image") && (
                <Image
                  style={{
                    height: mediaSize.current,
                    width: mediaSize.current,
                  }}
                  source={{ uri: media.data }}
                />
              )}
            </>
          ))}
        </View>

        {/* --------------------------------------------------------------------------- */}
        {/* EMPTYSTATE */}
        {/* --------------------------------------------------------------------------- */}
        {media.length === 0 && (
          <>
            <View style={styles.emptyResult}>
              <EmptyState
                title="No media yet"
                image={AppAssets.images.chatPhoto}
                description={"Please create media"}
              />
            </View>
          </>
        )}
      </ScrollView>
    </SafeAreaView>
  )
}
file:///Users/surushdev/Documents/openchat/packages/common/core/src/schema-validation/schema-validation.manager.ts:143
      throw new SchemaValidationError(debugPath, validationResult)
            ^
SchemaValidationError: validation failed for "MessageHandler"."getByRoomId" (returns) with error - JSON validation failed for required at #/0/messages.
Error paths: [
  {
    "keywordLocation": "#/items/$ref/required",
    "instanceLocation": "#/0/messages"
  },
  {
    "keywordLocation": "#/items/$ref/required",
    "instanceLocation": "#/0/messageMetadatas"
  },
  {
    "keywordLocation": "#/items/$ref/required",
    "instanceLocation": "#/0/attachments"
  },
  {
    "keywordLocation": "#/items/$ref/required",
    "instanceLocation": "#/0/files"
  },
  {
    "keywordLocation": "#/items/$ref/required",
    "instanceLocation": "#/0/links"
  },
  {
    "keywordLocation": "#/items/$ref/required",
    "instanceLocation": "#/0/polls"
  }
]