import BorderBottomItem from "@/components/borderBottomItem";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from "@/components/Text";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetNotification, apiReadOneNotification } from "@/lib/api";
import { setUpdateNotification } from "@/lib/notificationSlice";
import { pushToPage } from "@/lib/pushToPage";
import { useAuthSession } from "@/providers/AuthProvider";
import { Feather } from "@expo/vector-icons";
import { useEffect, useState } from "react";
import { RefreshControl, SafeAreaView, View, VirtualizedList } from "react-native";
import { useDispatch, useSelector } from "react-redux";

type Props = {
   id: string
   title: string
   desc: string
   category: string
   idContent: string
   isRead: boolean
   createdAt: string
}

export default function Notification() {
   const { token, decryptToken } = useAuthSession()
   const [loading, setLoading] = useState(false)
   const [data, setData] = useState<Props[]>([])
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = useState(false)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)
   const dispatch = useDispatch()
   const updateNotification = useSelector((state: any) => state.notificationUpdate)
   const [refreshing, setRefreshing] = useState(false)

   async function handleLoad(loading: boolean, thisPage: number) {
      try {
         setLoading(loading)
         setPage(thisPage)
         setWaiting(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetNotification({ user: hasil, page: thisPage })
         if (thisPage == 1) {
            setData(response.data)
         } else if (thisPage > 1 && response.data.length > 0) {
            setData([...data, ...response.data])
         } else {
            return;
         }
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
         setWaiting(false)
      }
   }


   const loadMoreData = () => {
      if (waiting) return
      setTimeout(() => {
         handleLoad(false, page + 1)
      }, 1000);
   };

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


   const getItem = (_data: unknown, index: number): Props => ({
      id: data[index].id,
      title: data[index].title,
      desc: data[index].desc,
      category: data[index].category,
      idContent: data[index].idContent,
      isRead: data[index].isRead,
      createdAt: data[index].createdAt,
   });

   async function handleReadNotification(id: string, category: string, idContent: string) {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiReadOneNotification({ user: hasil, id: id })
         pushToPage(category, idContent)
         dispatch(setUpdateNotification(!updateNotification))
      } catch (error) {
         console.error(error)
      }
   }

   const handleRefresh = async () => {
      setRefreshing(true)
      handleLoad(false, 1)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   return (
      <SafeAreaView>
         <View style={[Styles.p15]}>
            {
               loading ?
                  arrSkeleton.map((item, index) => {
                     return (
                        <SkeletonTwoItem key={index} />
                     )
                  })
                  :
                  data.length > 0 ?
                     <VirtualizedList
                        data={data}
                        getItemCount={() => data.length}
                        getItem={getItem}
                        renderItem={({ item, index }: { item: Props, index: number }) => {
                           return (
                              <BorderBottomItem
                                 borderType="bottom"
                                 icon={
                                    <View style={[Styles.iconContent, item.isRead ? ColorsStatus.secondary : ColorsStatus.primary]}>
                                       <Feather name="bell" size={25} color="white" />
                                    </View>
                                 }
                                 title={item.title}
                                 rightTopInfo={item.createdAt}
                                 desc={item.desc}
                                 textColor={item.isRead ? 'gray' : 'black'}
                                 onPress={() => {
                                    handleReadNotification(item.id, item.category, item.idContent)

                                 }}
                              />
                           )
                        }}
                        keyExtractor={(item, index) => String(index)}
                        onEndReached={loadMoreData}
                        onEndReachedThreshold={0.5}
                        showsVerticalScrollIndicator={false}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                           />
                        }
                     />
                     :
                     <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
            }
         </View>
      </SafeAreaView>
   )
}