import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetDivisionOneFeature } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { Feather } from "@expo/vector-icons";
import * as FileSystem from 'expo-file-system';
import { startActivityAsync } from 'expo-intent-launcher';
import { useLocalSearchParams } from "expo-router";
import * as Sharing from 'expo-sharing';
import React, { useEffect, useState } from "react";
import { Alert, Dimensions, Platform, Pressable, View } from "react-native";
import * as mime from 'react-native-mime-types';
import { ICarouselInstance } from "react-native-reanimated-carousel";
import ModalLoading from "../modalLoading";
import Skeleton from "../skeleton";
import { useTheme } from "@/providers/ThemeProvider";
import Text from "../Text";

type Props = {
   id: string
   name: string
   extension: string
   path: string
   share: boolean
   idStorage: string
}

export default function FileDivisionDetail({ refreshing }: { refreshing: boolean }) {
   const { colors } = useTheme();
   const ref = React.useRef<ICarouselInstance>(null);
   const width = Dimensions.get("window").width;
   const [data, setData] = useState<Props[]>([])
   const { token, decryptToken } = useAuthSession()
   const { id } = useLocalSearchParams<{ id: string }>()
   const [loading, setLoading] = useState(true)
   const [loadingOpen, setLoadingOpen] = useState(false)

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDivisionOneFeature({ user: hasil, id, cat: 'new-file' })
         setData(response.data)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

   useEffect(() => {
      if (refreshing)
         handleLoad(false)
   }, [refreshing])

   useEffect(() => {
      handleLoad(true)
   }, [])


   const openFile = (item: Props) => {
      if (Platform.OS == 'android') setLoadingOpen(true)
      let remoteUrl = ConstEnv.url_storage + '/files/' + item.idStorage;
      const fileName = item.name + '.' + item.extension;
      let localPath = `${FileSystem.documentDirectory}/${fileName}`;
      const mimeType = mime.lookup(fileName)

      FileSystem.downloadAsync(remoteUrl, localPath).then(async ({ uri }) => {
         const contentURL = await FileSystem.getContentUriAsync(uri);
         setLoadingOpen(false)
         try {
            if (Platform.OS == 'android') {
               // open with android intent
               await startActivityAsync(
                  'android.intent.action.VIEW',
                  {
                     data: contentURL,
                     flags: 1,
                     type: mimeType as string,
                  }
               );
               // or
               // Sharing.shareAsync(localPath);

            } else if (Platform.OS == 'ios') {
               Sharing.shareAsync(localPath);
            }
         } catch (error) {
            Alert.alert('INFO', 'Gagal membuka file, tidak ada aplikasi yang dapat membuka file ini');
         } finally {
            if (Platform.OS == 'android') setLoadingOpen(false)
         }
      });
   };


   return (
      <View style={[Styles.mb15]}>
         <ModalLoading isVisible={loadingOpen} setVisible={setLoadingOpen} />
         <Text style={[Styles.textDefaultSemiBold, Styles.mv10]}>Dokumen Terkini</Text>
         {
            loading ?
               <View style={[Styles.rowSpaceBetween]}>
                  <Skeleton width={30} widthType="percent" height={80} borderRadius={10} />
                  <Skeleton width={30} widthType="percent" height={80} borderRadius={10} />
                  <Skeleton width={30} widthType="percent" height={80} borderRadius={10} />
               </View>
               :
               data.length > 0 ?
                  <View style={[Styles.rowItemsCenter]}>
                     {
                        data.map((item, index) => (
                           <Pressable style={[Styles.mr05, { width: '24%' }]} key={index} onPress={() => openFile(item)}>
                              <View style={{ alignItems: 'center' }}>
                                 <View style={[Styles.wrapPaper, { alignItems: 'center', backgroundColor: colors.card, borderWidth: 1, borderColor: colors.icon + '20' }]}>
                                    <Feather name="file-text" size={50} color={colors.text} style={Styles.mr05} />
                                 </View>
                              </View>
                              <View style={[Styles.contentItemCenter]}>
                                 <Text style={[Styles.textMediumNormal, Styles.w90, { textAlign: 'center' }]} numberOfLines={1}>{item.name}.{item.extension}</Text>
                              </View>
                           </Pressable>
                        ))
                     }
                  </View>
                  // <Carousel
                  //    ref={ref}
                  //    width={width * 1.1}
                  //    height={115}
                  //    data={data}
                  //    loop={true}
                  //    autoPlay={false}
                  //    autoPlayReverse={false}
                  //    pagingEnabled={true}
                  //    snapEnabled={true}
                  //    vertical={false}
                  //    mode="parallax"
                  //    modeConfig={{
                  //       parallaxScrollingScale: 1,
                  //       parallaxScrollingOffset: 310,
                  //       parallaxAdjacentItemScale: 1,
                  //    }}
                  //    style={{ width:'100%' }}
                  //    renderItem={({ index }) => (
                  //       <View style={{ width: '27%' }}>
                  //          <View style={{ alignItems: 'center' }}>
                  //             <View style={[Styles.wrapPaper, { alignItems: 'center' }]}>
                  //                <Feather name="file-text" size={50} color="black" style={Styles.mr05} />
                  //             </View>
                  //          </View>
                  //          <Text style={[Styles.textMediumNormal, { textAlign: 'center' }]} numberOfLines={1}>{data[index].name}.{data[index].extension}</Text>
                  //       </View>

                  //    )}
                  // />
                  :
                  <Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada file</Text>
         }
      </View>
   )
}