import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import ImageUser from "@/components/imageNew";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import SkeletonContent from "@/components/skeletonContent";
import Text from "@/components/Text";
import WrapTab from "@/components/wrapTab";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetDiscussion, apiGetDivisionOneFeature } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Feather, Ionicons } from "@expo/vector-icons";
import { router, useLocalSearchParams } 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,
   status: number,
   user_name: string,
   img: string,
   total_komentar: number,
   createdAt: string,
   isActive: boolean
}


export default function DiscussionDivision() {
   const { colors } = useTheme();
   const { id, active } = useLocalSearchParams<{ id: string, active?: string }>()
   const [data, setData] = useState<Props[]>([])
   const { token, decryptToken } = useAuthSession()
   const [search, setSearch] = useState('')
   const update = useSelector((state: any) => state.discussionUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 })
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = useState(false)
   const [status, setStatus] = useState<'true' | 'false'>('true')
   const [refreshing, setRefreshing] = useState(false)
   const [isMemberDivision, setIsMemberDivision] = useState(false)
   const [isAdminDivision, setIsAdminDivision] = useState(false)
   const entityUser = useSelector((state: any) => state.user)

   async function handleCheckMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivisionOneFeature({
            id,
            user: hasil,
            cat: "check-member",
         });

         const response2 = await apiGetDivisionOneFeature({
            id,
            user: hasil,
            cat: "check-admin",
         });
         setIsMemberDivision(response.data);
         setIsAdminDivision(response2.data);
      } catch (error) {
         console.error(error);
      }
   }

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


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

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

   useEffect(() => {
      handleCheckMember()
   }, [])

   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,
      status: data[index].status,
      user_name: data[index].user_name,
      img: data[index].img,
      total_komentar: data[index].total_komentar,
      createdAt: data[index].createdAt,
      isActive: data[index].isActive,
   })

   return (
      <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
         {
            ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision) &&
            <View>
               <WrapTab>
                  <ButtonTab
                     active={status == "false" ? "false" : "true"}
                     value="true"
                     onPress={() => { setStatus("true") }}
                     label="Aktif"
                     icon={<Feather name="check-circle" color={status == "false" ? colors.dimmed : 'white'} size={20} />}
                     n={2} />
                  <ButtonTab
                     active={status == "false" ? "false" : "true"}
                     value="false"
                     onPress={() => { setStatus("false") }}
                     label="Arsip"
                     icon={<AntDesign name="closecircleo" color={status == "true" ? colors.dimmed : 'white'} size={20} />}
                     n={2} />
               </WrapTab>
               <InputSearch onChange={setSearch} />
            </View>
         }


         <View style={[{ flex: 2 }, Styles.mt05]}>
            {
               loading ?
                  arrSkeleton.map((item: any, i: number) => {
                     return (
                        <SkeletonContent key={i} />
                     )
                  })
                  :
                  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(`./discussion/${item.id}`) }}
                                 borderType="bottom"
                                 icon={
                                    <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                                 }
                                 title={item.user_name}
                                 subtitle={
                                    status == "true" ? item.status == 1 ? <LabelStatus category='success' text='BUKA' size="small" /> : <LabelStatus category='error' text='TUTUP' size="small" /> : <></>
                                 }
                                 rightTopInfo={item.createdAt}
                                 desc={item.desc}
                                 leftBottomInfo={
                                    <View style={[Styles.rowItemsCenter]}>
                                       <Ionicons name="chatbox-ellipses-outline" size={18} color={colors.dimmed} style={Styles.mr05} />
                                       <Text style={[Styles.textInformation, { color: colors.dimmed }, Styles.mb05]}>Diskusikan</Text>
                                    </View>
                                 }
                                 rightBottomInfo={item.total_komentar + ' Komentar'}
                                 bgColor="transparent"
                              />
                           )
                        }}
                        keyExtractor={(item, index) => String(index)}
                        onEndReached={loadMoreData}
                        onEndReachedThreshold={0.5}
                        showsVerticalScrollIndicator={false}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                              tintColor={colors.icon}
                           />
                        }
                     />
                     :
                     (<Text style={[Styles.textDefault, Styles.mv10, { textAlign: "center", color: colors.dimmed }]}>Tidak ada diskusi</Text>)
            }
         </View>
      </View>
   );
}