import Styles from "@/constants/Styles";
import { apiDeleteFileProject, apiGetProjectOne } from "@/lib/api";
import { setUpdateProject } from "@/lib/projectUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import * as FileSystem from 'expo-file-system';
import { Directory, File, Paths } from 'expo-file-system/next';
import * as MediaLibrary from 'expo-media-library';
import { useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Alert, Platform, Text, ToastAndroid, View } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import AlertKonfirmasi from "../alertKonfirmasi";
import BorderBottomItem from "../borderBottomItem";
import DrawerBottom from "../drawerBottom";
import MenuItemRow from "../menuItemRow";
import Skeleton from "../skeleton";


type Props = {
   id: string
   name: string
   extension: string
   idStorage: string
}

export default function SectionFile({ status, member }: { status: number | undefined, member: boolean }) {
   const entityUser = useSelector((state: any) => state.user)
   const [isModal, setModal] = useState(false)
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [data, setData] = useState<Props[]>([]);
   const update = useSelector((state: any) => state.projectUpdate)
   const [idSelect, setIdSelect] = useState('')
   const dispatch = useDispatch()
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 3 })

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

   useEffect(() => {
      handleLoad(false);
   }, [update.file]);


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

   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiDeleteFileProject({ user: hasil }, idSelect);
         if (response.success) {
            ToastAndroid.show('Berhasil menghapus file', ToastAndroid.SHORT)
            dispatch(setUpdateProject({ ...update, file: !update.file }))
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT)
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show('Terjadi kesalahan', ToastAndroid.SHORT)
      } finally {
         setModal(false)
      }
   }

   const downloadFile = async (fileUrl: string) => {
      try {
         // Get file name from URL
         const fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);

         // Create local file path
         const fileUri = `${FileSystem.documentDirectory}${fileName}`;

         // Download the file with progress tracking
         const downloadResumable = FileSystem.createDownloadResumable(
            fileUrl,
            fileUri,
            {},
            (downloadProgress) => {
               const progress = downloadProgress.totalBytesWritten / downloadProgress.totalBytesExpectedToWrite;
            }
         );
         const downloadResult = await downloadResumable.downloadAsync();

         if (downloadResult && downloadResult.uri) {
            const uri = downloadResult.uri;

            if (Platform.OS === 'android') {
               // For Android, we need to save to media library
               const { status } = await MediaLibrary.requestPermissionsAsync();

               if (status === 'granted') {
                  const fileString = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64 });
                  const newFile = await FileSystem.StorageAccessFramework.createFileAsync(
                     uri,
                     'sample',
                     downloadResult.headers['content-type']
                  );
                  await FileSystem.writeAsStringAsync(newFile, fileString, { encoding: FileSystem.EncodingType.Base64 });
                  Alert.alert('Success', `File downloaded and saved to Downloads folder`);
               } else {
                  Alert.alert('Error', 'Permission to access media library denied');
               }
            } else {
               // For iOS, the file is already saved to the app's document directory
               Alert.alert('Success', `File downloaded and saved to app's documents folder`);
            }

            return uri;
         }
      } catch (error) {
         console.error('Error downloading file:', error);
         Alert.alert('Error', `Failed to download file: ${error}`);
         return null;
      }
   };


   async function download() {
      const url = 'https://pdfobject.com/pdf/sample.pdf';
      const destination = new Directory(Paths.cache, 'pdfs');
      try {
         destination.create();
         const output = await File.downloadFileAsync(url, destination);
      } catch (error) {
         console.error(error);
      }
   }



   return (
      <>
         <View style={[Styles.mb15]}>
            <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>File</Text>
            <View style={[Styles.wrapPaper]}>
               {
                  loading ?
                     arrSkeleton.map((item, index) => {
                        return (
                           <Skeleton key={index} width={100} height={40} widthType="percent" borderRadius={10} />
                        )
                     })
                     :
                     data.length > 0 ?
                        data.map((item, index) => {
                           return (
                              <BorderBottomItem
                                 key={index}
                                 borderType="all"
                                 icon={<MaterialCommunityIcons name="file-outline" size={25} color="black" />}
                                 title={item.name + '.' + item.extension}
                                 titleWeight="normal"
                                 onPress={() => { setIdSelect(item.id); setModal(true) }}
                              />
                           )
                        })
                        :
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada file</Text>
               }
            </View>
         </View>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="file-eye" color="black" size={25} />}
                  title="Lihat File"
                  onPress={() => {
                     setModal(false)
                  }}
               />
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="download" color="black" size={25} />}
                  title="Download"
                  onPress={() => {
                     downloadFile('https://pdfobject.com/pdf/sample.pdf')
                     setModal(false)
                  }}
               />
               {
                  !member && (entityUser.role == "user" || entityUser.role == "coadmin") ? <></>
                     :
                     <MenuItemRow
                        icon={<Ionicons name="trash" color="black" size={25} />}
                        title="Hapus"
                        disabled={status == 3}
                        onPress={() => {
                           if (status == 3) return
                           AlertKonfirmasi({
                              title: 'Konfirmasi',
                              desc: 'Apakah Anda yakin ingin menghapus file ini? File yang dihapus tidak dapat dikembalikan',
                              onPress: () => {
                                 handleDelete()
                              }
                           })

                        }}
                     />
               }
            </View>
         </DrawerBottom>
      </>
   )
}