import React from "react";
import { File } from "../../lib/types/discord";
import { Dimensions, Image, Linking, Pressable, StyleSheet, View } from "react-native";
import { ThemedText } from "../themed-text";
import { useThemedActionSheet } from "../themed-sheet";
import { downloadFile, getSystemDir, SystemDir } from "../../lib/fs";

type AttachmentsProps = { files: File[] }
type ImageProps = { data: File, isLast: boolean }

function ImageContent({ data, isLast }: ImageProps) {
  const screenWidth = Dimensions.get("window").width;
  const aspectRatio = data.width && data.height ? data.width / data.height : 1;
  const { showActionSheetWithOptions } = useThemedActionSheet();

  const imageOptions = (data: File) => {
    showActionSheetWithOptions({
      options: ["Download", "Open in Browser", "Cancel"],
      destructiveButtonIndex: 2,
      cancelButtonIndex: 2
    }, (selectedIndex?: number) => {
      switch (selectedIndex) {
        case 0:
          downloadFile(data.filename, data.url, getSystemDir(SystemDir.Pictures));
          break;
        case 1: 
          Linking.openURL(data.url);
          break;
      }
    });
  }

  return (
    <Pressable onPress={() => imageOptions(data)}>
      <Image
        style={[
          styles.image,
          !isLast ? { marginBottom: 2 } : { marginBottom: 1 },
          { width: screenWidth * 0.6, aspectRatio }
        ]}
        resizeMode="contain"
        source={{ uri: data.url }}
      />
    </Pressable>
  )
}

export default function Attachments({ files }: AttachmentsProps) {
  const renderFile = (data: File, idx: number) => {
    if (data.content_type.startsWith("image/")) {
      return <ImageContent data={data} isLast={idx == files.length - 1} />
    } else {
      const pressHandler = () => downloadFile(data.filename, data.url, getSystemDir(SystemDir.Downloads))
      return <ThemedText type="link" onPress={pressHandler}>Download {data.filename}</ThemedText>
    }
  };

  return (
    <>
      {files.map((data, idx) => (
        <View key={idx}>
          {renderFile(data, idx)}
        </View>
      ))}
    </>
  );
}

const styles = StyleSheet.create({
  image: {
    height: undefined,
    marginTop: 5,
    marginLeft: 0.5
  }
})