import { FileType } from "@openchat/types"
import { useEffect, useRef, useState } from "react"
import { Image, LayoutAnimation, TouchableOpacity, View } from "react-native"
import { FlatList } from "react-native-gesture-handler"
import Video, { VideoRef } from "react-native-video"
import RNFS from "react-native-fs"
import { AppColors } from "../../../app/app.colors"
import { Icon } from "../../../ui-components/icon/icon.component"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { useStyles } from "./message-attachment-uploaded-files-preview.style"

export const MessageAttachmentUploadedFilesPreview = ({
  files,
  onFileRemove,
  screen,
  isEnabled = false,
}: {
  files: FileType[]
  onFileRemove: (fileId: string) => void
  screen?: string
  isEnabled?: boolean
}) => {
  // ------------------------------------------------------------------------------------
  // variables
  // ------------------------------------------------------------------------------------

  const styles = useStyles()
  const videoRef = useRef<VideoRef>(null)
  const flatListRef = useRef<FlatList<FileType>>(null)
  const layoutAnimConfig = {
    duration: 300,
    update: {
      type: LayoutAnimation.Types.easeInEaseOut,
    },
    delete: {
      duration: 100,
      type: LayoutAnimation.Types.easeInEaseOut,
      property: LayoutAnimation.Properties.opacity,
    },
  }
  const [isDownloading, setIsDownloading] = useState(false)
  const [videoFilePath, setVideoFilePath] = useState<string | null>(null)

  useEffect(() => {
    for (const file of files) {
      if (file.mimeType.startsWith("video")) {
        downloadVideo(file.data, "temp_video.mp4")
      }
    }
  }, [files])

  // ------------------------------------------------------------------------------------
  // functions
  // ------------------------------------------------------------------------------------
  function formatSizeUnits(bytes: number) {
    let size
    if (bytes >= 1073741824) {
      size = (bytes / 1073741824).toFixed(2) + " GB"
    } else if (bytes >= 1048576) {
      size = (bytes / 1048576).toFixed(2) + " MB"
    } else if (bytes >= 1024) {
      size = (bytes / 1024).toFixed(2) + " KB"
    } else if (bytes > 1) {
      size = bytes + " bytes"
    } else if (bytes == 1) {
      size = bytes + " byte"
    } else {
      size = "0 byte"
    }
    return size
  }

  async function downloadVideo(url: string, fileName: string) {
    setIsDownloading(true)
    const path = `${RNFS.DocumentDirectoryPath}/${fileName}`
    const downloadOptions = {
      fromUrl: url,
      toFile: path,
    }
    try {
      await RNFS.downloadFile(downloadOptions).promise
      setVideoFilePath(path)
      setIsDownloading(false)
    } catch (error) {
      console.error("Error downloading video", error)
      setIsDownloading(false)
    }
  }

  // ------------------------------------------------------------------------------------
  return (
    <>
      <FlatList
        showsHorizontalScrollIndicator={false}
        ref={flatListRef}
        contentContainerStyle={[
          styles.scrollWrapper,
          { gap: screen === "MessageBoardCardInfo" ? 5 : 10 },
        ]}
        horizontal={true}
        scrollEnabled={isEnabled ? false : true}
        data={files}
        keyExtractor={(file) => file.id}
        renderItem={({ item: file }) => {
          return (
            <View style={styles.attachmentItem} key={file.id}>
              {file.mimeType.startsWith("image") && (
                <View>
                  <Image
                    resizeMode="cover"
                    style={styles.media}
                    source={{ uri: file.data }}
                  />
                </View>
              )}
              {file.mimeType.startsWith("video") && videoFilePath && (
                <Video
                  ref={videoRef}
                  resizeMode="cover"
                  source={{ uri: `file://${videoFilePath}` }}
                  paused={true}
                  controls={false}
                  style={styles.videoPreview}
                  pictureInPicture={true}
                />
              )}

              {file.mimeType.startsWith("audio") && <></>}

              {!file.mimeType.startsWith("image") &&
                !file.mimeType.startsWith("video") &&
                !file.mimeType.startsWith("audio") && (
                  <View style={styles.anotherFiles}>
                    <Icon
                      name="fal fa-file-lines"
                      bald={true}
                      size={25}
                      fill={AppColors.placeholderText}
                    />
                    <View style={styles.fileInfoWrapper}>
                      <StyledText
                        ellipsizeMode="tail"
                        numberOfLines={1}
                        style={styles.fileName}
                      >
                        {file.name}
                      </StyledText>
                      <StyledText style={styles.fileSize}>
                        {formatSizeUnits(file.size)}
                      </StyledText>
                    </View>
                  </View>
                )}
              {screen !== "MessageBoardCardInfo" && (
                <TouchableOpacity
                  activeOpacity={0.9}
                  style={styles.xHolder}
                  onPress={() => {
                    onFileRemove(file.id)
                    LayoutAnimation.configureNext(layoutAnimConfig)
                  }}
                >
                  <Icon name="fal fa-xmark" bald={true} height={14} width={9} />
                </TouchableOpacity>
              )}
            </View>
          )
        }}
      />
    </>
  )
}
I have issue when I try two upload more than one files like I try to upload 3 videos but it duplicates first videos three time. How to fix it if I upload three different videos they should uploaded ?