import HeaderRightAnnouncementList from "@/components/announcement/headerAnnouncementList";
import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import InputSearch from "@/components/inputSearch";
import SkeletonContent from "@/components/skeletonContent";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetAnnouncement } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { MaterialIcons } from "@expo/vector-icons";
import { router, Stack } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, Text, View } 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 [data, setData] = useState<Props[]>([])
   const [search, setSearch] = useState('')
   const entityUser = useSelector((state: any) => state.user)
   const update = useSelector((state: any) => state.announcementUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)

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

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

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

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Pengumuman',
               headerTitleAlign: 'center',
               headerRight: () => entityUser.role != 'user' && entityUser.role != 'coadmin' ? <HeaderRightAnnouncementList /> : <></>
            }}
         />

         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputSearch onChange={setSearch} />
               {
                  loading ?
                     arrSkeleton.map((item, index) => {
                        return (
                           <SkeletonContent key={index} />
                        )
                     })
                     :
                     data.length > 0
                        ?
                        data.map((item, index) => {
                           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, '')}
                                 rightTopInfo={item.createdAt}
                              />
                           )
                        })
                        :
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada pengumuman</Text>
               }
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}