import BorderBottomItem from "@/components/borderBottomItem";
import InputSearch from "@/components/inputSearch";
import SkeletonContent from "@/components/skeletonContent";
import Text from '@/components/Text';
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetAnnouncement } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialIcons } from "@expo/vector-icons";
import { router } from "expo-router";
import { useEffect, useState } from "react";
import { RefreshControl, View, VirtualizedList } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   id: string,
   title: string,
   desc: string,
   createdAt: string
}


export default function Announcement() {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const [data, setData] = useState<Props[]>([])
   const [search, setSearch] = useState('')
   const update = useSelector((state: any) => state.announcementUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = useState(false)
   const [refreshing, setRefreshing] = useState(false)

   async function handleLoad(loading: boolean, thisPage: number) {
      try {
         setWaiting(true)
         setLoading(loading)
         setPage(thisPage)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetAnnouncement({ user: hasil, search: search, 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)
      }
   }

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

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

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

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

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

   return (
      <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
         <View>
            <InputSearch onChange={setSearch} />
         </View>
         <View style={[{ flex: 2 }, Styles.mt05]}>
            {
               loading ?
                  arrSkeleton.map((item, index) => {
                     return (
                        <SkeletonContent key={index} />
                     )
                  })
                  :
                  data.length > 0
                     ?
                     <VirtualizedList
                        data={data}
                        getItemCount={() => data.length}
                        getItem={getItem}
                        renderItem={({ item, index }: { item: Props, index: number }) => {
                           return (
                              <BorderBottomItem
                                 key={index}
                                 onPress={() => { router.push(`/announcement/${item.id}`) }}
                                 borderType="bottom"
                                 icon={
                                    <View style={[Styles.iconContent, ColorsStatus.lightGreen]}>
                                       <MaterialIcons name="campaign" size={25} color={'#384288'} />
                                    </View>
                                 }
                                 title={item.title}
                                 desc={item.desc.replace(/<[^>]*>?/gm, '').replace(/\r?\n|\r/g, ' ')}
                                 rightTopInfo={item.createdAt}
                              />
                           )
                        }}
                        keyExtractor={(item, index) => String(index)}
                        onEndReached={loadMoreData}
                        onEndReachedThreshold={0.5}
                        showsVerticalScrollIndicator={false}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                              tintColor={colors.primary}
                           />
                        }
                     />
                     :
                     <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada pengumuman</Text>
            }
         </View>
      </View>
   )
}