import BorderBottomItem from "@/components/borderBottomItem";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
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 { SafeAreaView, Text, 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)

   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)
      }
   }

   // function pushToPage(category: string, idContent: string) {
   //    const cat = category.split('/')
   //    if (cat.length > 1) {
   //       if (cat[2] == 'calendar') {
   //          router.push(`/division/${cat[1]}/calendar/${idContent}`)
   //       } else if (cat[2] == 'discussion') {
   //          router.push(`/division/${cat[1]}/discussion/${idContent}`)
   //       } else if (cat[2] == 'document') {
   //          router.push(`/division/${cat[1]}/document/${idContent}`)
   //       } else if (cat[2] == 'task') {
   //          router.push(`/division/${cat[1]}/task/${idContent}`)
   //       }
   //    } else {
   //       if (cat[0] == 'announcement') {
   //          router.push(`/announcement/${idContent}`)
   //       } else if (cat[0] == 'discussion-general') {
   //          router.push(`/discussion/${idContent}`)
   //       } else if (cat[0] == 'division') {
   //          router.push(`/division/${idContent}`)
   //       } else if (cat[0] == 'member') {
   //          router.push(`/member/${idContent}`)
   //       } else if (cat[0] == 'project') {
   //          router.push(`/project/${idContent}`)
   //       }
   //    }
   // }


   return (
      <SafeAreaView>
         <View style={[Styles.p15]}>
            <View style={[Styles.wrapPaper, Styles.mb100]}>
               {
                  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}
                        />
                        :
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
               }
            </View>
         </View>
      </SafeAreaView>
   )
}