import Styles from "@/constants/Styles";
import { apiDeleteFileTask, apiGetTaskOne } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { 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 SectionFileTask() {
   const [isModal, setModal] = useState(false)
   const { token, decryptToken } = useAuthSession()
   const { detail } = useLocalSearchParams<{ detail: string }>();
   const [data, setData] = useState<Props[]>([])
   const [idSelect, setIdSelect] = useState('')
   const update = useSelector((state: any) => state.taskUpdate)
   const dispatch = useDispatch()
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 })

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetTaskOne({ id: detail, user: hasil, cat: 'file' })
         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 apiDeleteFileTask({ user: hasil }, idSelect);
         if (response.success) {
            ToastAndroid.show('Berhasil menghapus file', ToastAndroid.SHORT)
            dispatch(setUpdateTask({ ...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)
      }
   }

   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) }}
                                 width={65}
                              />
                           )
                        })
                        :
                        <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={() => {
                     setModal(false)
                  }}
               />

               <MenuItemRow
                  icon={<Ionicons name="trash" color="black" size={25} />}
                  title="Hapus"
                  onPress={() => {
                     AlertKonfirmasi({
                        title: 'Konfirmasi',
                        desc: 'Apakah Anda yakin ingin menghapus file ini? File yang dihapus tidak dapat dikembalikan',
                        onPress: () => {
                           handleDelete()
                        }
                     })

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