import { AttachmentKind, AttachmentType } from "@openchat/types"
import { useRef, useState } from "react"
import { Image, Platform, Pressable, ScrollView, View } from "react-native"
import ImageView from "react-native-image-viewing"
import Video, { VideoRef } from "react-native-video"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { Icon } from "../../../ui-components/icon/icon.component"
import { useStyles } from "./message-attachment-preview.style"
import { MenuOpener } from "../../../ui-components/menu/menu-opener.provider"
import { MenuItem } from "../../../ui-components/menu"
import { AppColors } from "../../../app/app.colors"
import AudioRecorderPlayer, {
  PlayBackType,
} from "react-native-audio-recorder-player"
import { MessageContentAudio } from "../message-content-audio/message-content-audio.component"
import SvgImg from "../../../../public/images/pdf.svg"
import RNFS from "react-native-fs"
import FileViewer from "react-native-file-viewer"
import { AppController } from "../../../app/app.globals"

const audioRecorderPlayer = new AudioRecorderPlayer()
audioRecorderPlayer.setSubscriptionDuration(0.01)

export const MessageAttachmentPreview = ({
  attachments = [],
}: //   date,
// sender,
{
  attachments: AttachmentType[]
  //   date: Date
  // sender: MemberType
}) => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const styles = useStyles()
  const videoRef = useRef<VideoRef>(null)
  const [currentIndex, setCurrentIndex] = useState(0)
  const [visible, setIsVisible] = useState(false)
  const images = attachments.map((attachment) => {
    return { uri: attachment.preview ? attachment.preview : "" }
  })
  const [audio, setAudio] = useState({
    isLoggingIn: false,
    recordSecs: 0,
    recordTime: "00:00:00",
    currentPositionSec: 0,
    currentDurationSec: 0,
    playTime: "00:00:00",
    duration: "00:00:00",
  })

  // ---------------------------------------------------------------------------
  // 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 onStartPlay(path: string): Promise<void> {
    const qwe = Platform.select({
      ios: path,
      android: undefined,

      // Discussion: https://github.com/hyochan/react-native-audio-recorder-player/discussions/479
      // ios: 'https://firebasestorage.googleapis.com/v0/b/cooni-ebee8.appspot.com/o/test-audio.mp3?alt=media&token=d05a2150-2e52-4a2e-9c8c-d906450be20b',
      // ios: 'https://staging.media.ensembl.fr/original/uploads/26403543-c7d0-4d44-82c2-eb8364c614d0',
      // ios: 'hello.m4a',
      // android: `${dirs.CacheDir}/hello.mp3`,
    })
    console.log("onStartPlay", path)

    try {
      const msg = await audioRecorderPlayer.startPlayer(path)

      //? Default path
      // const msg = await audioRecorderPlayer.startPlayer()
      const volume = await audioRecorderPlayer.setVolume(1.0)
      // console.log(`path: ${msg}`, `volume: ${volume}`)

      audioRecorderPlayer.addPlayBackListener((e: PlayBackType) => {
        console.log("playBackListener", e)
        setAudio({
          ...audio,
          currentPositionSec: e.currentPosition,
          currentDurationSec: e.duration,
          playTime: audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
          duration: audioRecorderPlayer.mmssss(Math.floor(e.duration)),
        })
      })
    } catch (err) {
      console.log("startPlayer error", err)
    }
  }

  async function handlePressLocalFile(fileId: string) {
    const file = await AppController.file.getFromLocal({ id: fileId })

    if (file && file.data) {
      let localFilePath = `${RNFS.DocumentDirectoryPath}/${file.name.split("/").pop()}`

      const options = {
        fromUrl: file.data,
        toFile: localFilePath,
      }

      try {
        await RNFS.downloadFile(options).promise
        await FileViewer.open(localFilePath)
      } catch (error) {
        console.log("Error", "Unable to open file")
        console.log(error)
      }
    }
  }

  // ---------------------------------------------------------------------------
  if (!attachments) return null
  return (
    <View style={styles.container}>
      {attachments.map((attachment) => {
        return (
          <>
            {attachment.kind === AttachmentKind.media &&
            attachment.mimeType.startsWith("image") &&
            attachment.preview ? (
              <>
                <ImageView
                  key={attachment.id}
                  images={images}
                  imageIndex={currentIndex}
                  visible={visible}
                  onRequestClose={() => setIsVisible(false)}
                  HeaderComponent={({ imageIndex }) => (
                    <View style={styles.header}>
                      <Icon
                        onPress={() => setIsVisible(false)}
                        name="far fa-arrow-left"
                        size={16}
                        fill={AppColors.light}
                      />
                      <View style={styles.imageIndexWrap}>
                        <StyledText
                          style={styles.imageIndexText}
                        >{`${imageIndex + 1} of ${images.length}`}</StyledText>
                      </View>
                      {/* <Icon
                      // onPress={() => setModalInMore(!modalInMore)}
                      name="far fa-ellipsis-vertical"
                      size={18}
                      fill="white"
                    /> */}
                      <MenuOpener
                        touchOpacity={0.7}
                        content={
                          <>
                            <MenuItem
                              icon="fal fa-square-arrow-up-right"
                              title="Show in chat"
                            />
                            <MenuItem
                              icon="fal fa-bookmark"
                              title="Save photo"
                            />
                            <MenuItem
                              icon="fal fa-trash"
                              title="Delete"
                              mode="danger"
                            />
                          </>
                        }
                      >
                        <Icon
                          name="far fa-ellipsis-vertical"
                          size={18}
                          fill="white"
                        />
                      </MenuOpener>
                    </View>
                  )}
                  FooterComponent={({ imageIndex }) => (
                    <View style={styles.photoGalleryWrap}>
                      <ScrollView
                        showsHorizontalScrollIndicator={false}
                        contentContainerStyle={styles.photoGallery}
                        horizontal={true}
                      >
                        {images.map((image, index) => {
                          return (
                            <Image
                              style={
                                imageIndex === index
                                  ? styles.activePhoto
                                  : styles.photo
                              }
                              source={{ uri: image.uri }}
                            />
                          )
                        })}
                      </ScrollView>

                      <View style={styles.footer}>
                        <Icon
                          onPress={() => setIsVisible(false)}
                          name="fal fa-share-nodes"
                          size={16}
                          fill="white"
                        />
                        <View style={styles.nameAndDateWrap}>
                          <StyledText style={styles.userName}>
                            Mark Jacobs
                          </StyledText>
                          <StyledText style={styles.date}>
                            10/02/2024
                          </StyledText>
                        </View>
                        <Icon
                          name="fal fa-trash"
                          size={16}
                          fill={AppColors.textPrimaryLight}
                        />
                      </View>
                    </View>
                  )}
                />
                {/* <MessageAttachmentPhotoViewerModal attachment={attachment} /> */}
                <Pressable
                  onPress={() => setIsVisible(true)}
                  style={styles.photoPreviewWrap}
                >
                  <Image
                    key={attachment.id}
                    source={{ uri: attachment.preview }}
                    style={styles.photoPreview}
                  />
                </Pressable>
              </>
            ) : attachment.mimeType.startsWith("video") &&
              attachment.preview ? (
              <>
                <Pressable style={styles.videoPreview}>
                  {/* <Image
                    key={attachment.id}
                    source={{ uri: attachment.preview }}
                    style={[
                      styles.videoPreview,
                      {
                        borderRadius: 5,
                      },
                    ]}
                  /> */}
                  <Video
                    resizeMode="cover"
                    // Can be a URL or a local file.
                    source={{ uri: attachment.preview }}
                    // Store reference
                    ref={videoRef}
                    controls={true}
                    // Callback when remote video is buffering
                    // onBuffer={onBuffer}
                    // Callback when video cannot be loaded
                    // onError={onError}
                    style={{
                      height: 200,
                      width: "100%",
                      borderRadius: 5,
                      borderWidth: 1,
                      // maxHeight: 100,
                    }}
                    pictureInPicture={true}
                  />
                </Pressable>
              </>
            ) : attachment.mimeType.startsWith("audio") ? (
              <MessageContentAudio
                key={attachment.id}
                fileId={attachment.fileId}
              />
            ) : (
              <Pressable
                style={styles.applicationWrapper}
                key={attachment.id}
                onPress={() => handlePressLocalFile(attachment.fileId)}
              >
                <View style={styles.applicationSubWrapper}>
                  {attachment.mimeType.startsWith("pdf") ? (
                    <Pressable>
                      <SvgImg width={22} height={22} />
                    </Pressable>
                  ) : attachment.mimeType.startsWith(
                      "vnd.openxmlformats-officedocument.wordprocessingml.document",
                    ) ? (
                    <Icon
                      name="fa-solid fa-file-word"
                      height={24}
                      width={18}
                      fill={AppColors.primary}
                    />
                  ) : attachment.mimeType.startsWith(
                      "vnd.ms-excel" ||
                        "vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    ) ? (
                    <Icon
                      name="fa-solid fa-file-excel"
                      height={24}
                      width={18}
                      fill={AppColors.success}
                    />
                  ) : attachment.mimeType.startsWith(
                      "vnd.ms-powerpoint" ||
                        "vnd.openxmlformats-officedocument.presentationml.presentation",
                    ) ? (
                    <Icon
                      name="fa-solid fa-file-ppt"
                      height={24}
                      width={18}
                      fill={AppColors.danger}
                    />
                  ) : (
                    <Icon
                      name="fas fa-file-lines"
                      height={24}
                      width={18}
                      fill={AppColors.placeholderText}
                    />
                  )}

                  <View style={styles.applicationInfo}>
                    <StyledText
                      ellipsizeMode="tail"
                      numberOfLines={1}
                      style={styles.applicationName}
                    >
                      {attachment.name}
                    </StyledText>
                    <StyledText
                      ellipsizeMode="tail"
                      numberOfLines={1}
                      style={styles.applicationSize}
                    >
                      {formatSizeUnits(attachment.size)}
                    </StyledText>
                  </View>
                </View>
                <Icon name="far fa-ellipsis-vertical" height={18} width={5} />
              </Pressable>
            )}
          </>
        )
      })}
    </View>
  )
}
video not showing, How to fix it ?