import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import SkeletonContent from "@/components/skeletonContent";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetDiscussionGeneral } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { AntDesign, Feather, Ionicons, MaterialIcons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { RefreshControl, Text, View, VirtualizedList } from "react-native";
import { useSelector } from "react-redux";


type Props = {
   id: string
   title: string
   desc: string
   status: number
   total_komentar: number
   createdAt: string
}

export default function Discussion() {
   const entityUser = useSelector((state: any) => state.user)
   const { token, decryptToken } = useAuthSession()
   const { active, group } = useLocalSearchParams<{ active?: string, group?: string }>()
   const [search, setSearch] = useState('')
   const [nameGroup, setNameGroup] = useState('')
   const [data, setData] = useState<Props[]>([])
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)
   const [status, setStatus] = useState<'true' | 'false'>('true')
   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 apiGetDiscussionGeneral({ user: hasil, active: status, search: search, group: String(group), page: thisPage })
         if (thisPage == 1) {
            setData(response.data)
         } else if (thisPage > 1 && response.data.length > 0) {
            setData([...data, ...response.data])
         } else {
            return;
         }
         setNameGroup(response.filter.name)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
         setWaiting(false)
      }
   }


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

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


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

   return (
      <View style={[Styles.p15, { flex: 1 }]}>
         <View>
            <View style={[Styles.wrapBtnTab]}>
               <ButtonTab
                  active={status == "false" ? "false" : "true"}
                  value="true"
                  onPress={() => { setStatus("true") }}
                  label="Aktif"
                  icon={<Feather name="check-circle" color={status == "false" ? 'black' : '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" ? 'black' : 'white'} size={20} />}
                  n={2} />
            </View>
            <InputSearch onChange={setSearch} />
            {
               (entityUser.role == "supadmin" || entityUser.role == "developer") &&
               <View style={[Styles.mv05]}>
                  <Text>Filter : {nameGroup}</Text>
               </View>
            }
         </View>
         <View style={[{ flex: 2 }]}>
            {
               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={
                                    <View style={[Styles.iconContent, ColorsStatus.lightGreen]}>
                                       <MaterialIcons name="chat" size={25} color={'#384288'} />
                                    </View>
                                 }
                                 title={item.title}
                                 subtitle={
                                    status != "false" && <LabelStatus category={item.status === 1 ? "success" : "error"} text={item.status === 1 ? "BUKA" : "TUTUP"} size="small" />
                                 }
                                 rightTopInfo={item.createdAt}
                                 desc={item.desc}
                                 leftBottomInfo={
                                    <View style={[Styles.rowItemsCenter]}>
                                       <Ionicons name="chatbox-ellipses-outline" size={18} color="grey" style={Styles.mr05} />
                                       <Text style={[Styles.textInformation, Styles.cGray, Styles.mb05]}>Diskusikan</Text>
                                    </View>
                                 }
                                 rightBottomInfo={`${item.total_komentar} Komentar`}

                              />
                           )
                        }}
                        keyExtractor={(item, index) => String(index)}
                        onEndReached={loadMoreData}
                        onEndReachedThreshold={0.5}
                        showsVerticalScrollIndicator={false}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                           />
                        }
                     />
                     // data.map((item: any, i: number) => {
                     //    return (
                     //       <BorderBottomItem
                     //          key={i}
                     //          onPress={() => { router.push(`/discussion/${item.id}`) }}
                     //          borderType="bottom"
                     //          icon={
                     //             <View style={[Styles.iconContent, ColorsStatus.lightGreen]}>
                     //                <MaterialIcons name="chat" size={25} color={'#384288'} />
                     //             </View>
                     //          }
                     //          title={item.title}
                     //          subtitle={
                     //             status != "false" && <LabelStatus category={item.status === 1 ? "success" : "error"} text={item.status === 1 ? "BUKA" : "TUTUP"} size="small" />
                     //          }
                     //          rightTopInfo={item.createdAt}
                     //          desc={item.desc}
                     //          leftBottomInfo={
                     //             <View style={[Styles.rowItemsCenter]}>
                     //                <Ionicons name="chatbox-ellipses-outline" size={18} color="grey" style={Styles.mr05} />
                     //                <Text style={[Styles.textInformation, Styles.cGray, Styles.mb05]}>Diskusikan</Text>
                     //             </View>
                     //          }
                     //          rightBottomInfo={`${item.total_komentar} Komentar`}

                     //       />
                     //    )
                     // })
                     :
                     <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
            }
         </View>
      </View>
   );
}