import { AttachmentType, FileType } from "@openchat/types"
import {
  Image,
  NativeScrollEvent,
  Pressable,
  ScrollView,
  View,
} from "react-native"
import { Icon } from "../../../ui-components/icon/icon.component"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { useStyles } from "./message-room-assets-files.style"
import { useEffect, useState } from "react"
import FileViewer from "react-native-file-viewer"
import RNFS from "react-native-fs"
import { AppControllers } from "../../../app/app-context"
import { SafeAreaView } from "react-native-safe-area-context"
import { AppColors } from "../../../app/app-colors"
import { EmptyState } from "../../../ui-components/empty-state/empty-state.component"
import { AppAssets } from "../../../app/app-assets"
import { Spinner } from "../../../ui-components/spinner/spinner.component"
import SvgImg from "../../../../public/images/pdf.svg"
import { useLogger } from "@openchat/ui"
import { DateUtils } from "@openchat/framework"

export const MessageRoomAssetsFiles = ({
  roomId,
  date,
  onClose,
}: {
  roomId: string
  date?: Date
  onClose: () => void
}) => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const logger = useLogger("MessageRoomAssetsFiles")
  const styles = useStyles()
  const [files, setFiles] = useState<FileType[]>([])
  const [attachments, setAttachments] = useState<AttachmentType[]>([])

  const [isFetching, setFetching] = useState(false)
  const [skip, setSkip] = useState(0)

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

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

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

  // ---------------------------------------------------------------------------
  // 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 scrollHandler({
    layoutMeasurement,
    contentOffset,
    contentSize,
  }: NativeScrollEvent) {
    if (isFetching) return
    const paddingToBottom = 200
    if (
      layoutMeasurement.height + contentOffset.y >=
      contentSize.height - paddingToBottom
    )
      setSkip((prevState) => prevState + 12)
  }

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

    // const files = await LocalData.attachment.fetch({
    //   type: "files",
    //   roomId: room.id,
    //   skip: skip,
    // })

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

    console.log("=================attachments===================")
    console.log(attachments)
    console.log("=================end attachments===================")

    const files = await AppControllers.file.getByRoomId({
      roomId: roomId,
      ids: attachments
        .map((attachment) => attachment.fileId)
        .filter((fileId) => fileId !== null) as string[],
      skip: skip,
    })
    if (skip === 0) {
      setSkip(0)
      setFiles(files)
      setAttachments(attachments)
    } else {
      setFiles((prev) => [...prev, ...files])
      setAttachments((prev) => [...prev, ...attachments])
    }
    setFetching(false)
  }

  function format(name: string) {
    let formate = name.split(".").pop()
    return formate
  }

  function formattedDate(index: number) {
    return DateUtils.createDate(attachments[index - 1].createdAt)
  }

  // ---------------------------------------------------------------------------
  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}>Files</StyledText>
      </View>

      {/* --------------------------------------------------------------------------- */}
      {/* FILES LIST */}
      {/* --------------------------------------------------------------------------- */}
      {isFetching ? (
        <Spinner
          title="File is loading..."
          isEnabled={isFetching}
          height={4}
          indeterminate
          backgroundColor="#1B9FFC"
        />
      ) : (
        <ScrollView
          style={styles.list}
          onScroll={({ nativeEvent }) => {
            scrollHandler(nativeEvent)
          }}
        >
          {files.map((file, index) => {
           
            return (
              <Pressable
                key={file.id}
                style={({ pressed }) => [
                  styles.fileWrapper,
                  {
                    backgroundColor: pressed
                      ? AppColors.backgroundDark
                      : "white",
                  },
                ]}
              >
                {/* --------------------------------------------------------------------------- */}
                {/* FILE IMAGE OR ICON */}
                {/* --------------------------------------------------------------------------- */}

                {file.mimeType.startsWith("image") ? (
                  <Image source={{ uri: file.data }} style={styles.image} />
                ) : file.mimeType.startsWith("application/pdf") ? (
                  <Pressable>
                    <SvgImg width={22} height={22} />
                  </Pressable>
                ) : file.mimeType.startsWith(
                    "application/msword" ||
                      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                  ) ? (
                  <Icon
                    name="fa-solid fa-file-word"
                    height={24}
                    width={18}
                    fill={AppColors.primary}
                  />
                ) : file.mimeType.startsWith(
                    "application/vnd.ms-excel" ||
                      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                  ) ? (
                  <Icon
                    name="fa-solid fa-file-excel"
                    height={24}
                    width={18}
                    fill={AppColors.success}
                  />
                ) : file.mimeType.startsWith(
                    "application/vnd.ms-powerpoint" ||
                      "application/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.fileWrap}>
                  {/* --------------------------------------------------------------------------- */}
                  {/* FILE NAME */}
                  {/* --------------------------------------------------------------------------- */}

                  <StyledText
                    style={styles.fileName}
                    numberOfLines={1}
                    ellipsizeMode="tail"
                  >
                    {file.name}
                  </StyledText>

                  {/* --------------------------------------------------------------------------- */}
                  {/* FILE SIZE */}
                  {/* --------------------------------------------------------------------------- */}

                  <StyledText
                    numberOfLines={1}
                    ellipsizeMode="tail"
                    style={styles.fileSize}
                  >
                    {formatSizeUnits(file.size)} - {formattedDate(index)}
                  </StyledText>
                </View>
              </Pressable>
            )
          })}

          {/* --------------------------------------------------------------------------- */}
          {/* EMPTYSTATE */}
          {/* --------------------------------------------------------------------------- */}
          {files.length === 0 && !isFetching && (
            <>
              <View style={styles.emptyResult}>
                <EmptyState
                  title="No files yet"
                  image={AppAssets.images.chatPhoto}
                  description={"Please create files"}
                />
              </View>
            </>
          )}
        </ScrollView>
      )}
    </SafeAreaView>
  )
}
{formattedDate(index)} - Type 'Date' is not assignable to type 'ReactNode'.ts(2322)