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 Video from "react-native-video"
import RNFS from "react-native-fs"
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"
import { useLogger } from "@openchat/ui"
import { AppColors } from "../../../app/app-colors"
import { Spinner } from "../../../ui-components/spinner/spinner.component"
import React from "react"

export const MessageRoomAssetsMedia = ({
  roomId,
  onClose,
}: {
  roomId: string
  onClose: () => void
}) => {
  // ------------------------------------------------------------------------------------
  // variables
  // ------------------------------------------------------------------------------------

  const logger = useLogger("MessageRoomAssetsMedia")
  const mediaSize = useRef(0)
  const styles = useStyles()
  const [media, setMedia] = useState<FileType[]>([])
  const [skip, setSkip] = useState(0)
  const [isFetching, setFetching] = useState(false)
  const [videoFilePaths, setVideoFilePaths] = useState<Record<string, string>>(
    {},
  )

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

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

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

  useEffect(() => {
    for (const file of media) {
      if (file.mimeType.startsWith("video") && !videoFilePaths[file.id]) {
        downloadVideo(file.data, file.id)
      }
    }
  }, [media])

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

  async function downloadVideo(url: string, fileId: string) {
    const path = `${RNFS.DocumentDirectoryPath}/${fileId}.mp4`
    const downloadOptions = {
      fromUrl: url,
      toFile: path,
    }
    try {
      await RNFS.downloadFile(downloadOptions).promise
      setVideoFilePaths((prevPaths) => ({ ...prevPaths, [fileId]: path }))
    } catch (error) {
      logger.error("Error downloading video", error)
    }
  }
  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),
      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)
  }
  console.log("==================videoFilePaths==================")
  console.log(videoFilePaths)
  console.log("=================end videoFilePaths===================")
  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>
      {isFetching ? (
        <Spinner
          title="Attachments are loading..."
          isEnabled={isFetching}
          height={4}
          indeterminate
          backgroundColor="#1B9FFC"
        />
      ) : (
        <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) => (
              <React.Fragment key={media.id}>
                {media.mimeType.startsWith("image") && (
                  <Image
                    style={{
                      height: mediaSize.current,
                      width: mediaSize.current,
                    }}
                    source={{ uri: media.data }}
                  />
                )}
                {media.mimeType.startsWith("video") &&
                videoFilePaths[media.id] ? (
                  <View style={styles.previewMedia}>
                    <Video
                      source={{ uri: `file://${videoFilePaths[media.id]}` }}
                      style={[
                        styles.previewMedia,
                        { height: mediaSize.current, width: mediaSize.current },
                      ]}
                      resizeMode="cover"
                      paused={true}
                    />
                    <View style={styles.videoOverlay}>
                      <Icon
                        name="fa-solid fa-play"
                        size={14}
                        fill={AppColors.light}
                      />
                    </View>
                    <StyledText style={styles.duration}>
                      {videoFilePaths[media.id]}
                    </StyledText>
                  </View>
                ) : null}
              </React.Fragment>
            ))}
          </View>

          {/* --------------------------------------------------------------------------- */}
          {/* EMPTYSTATE */}
          {/* --------------------------------------------------------------------------- */}
          {media.length === 0 && !isFetching && (
            <>
              <View style={styles.emptyResult}>
                <EmptyState
                  title="No media yet"
                  image={AppAssets.images.chatPhoto}
                  description={"Please create media"}
                />
              </View>
            </>
          )}
        </ScrollView>
      )}
    </SafeAreaView>
  )
}
how to set media.duration inside videoFilePaths ?