import AlertKonfirmasi from "@/components/alertKonfirmasi";
import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import DrawerBottom from "@/components/drawerBottom";
import ImageUser from "@/components/imageNew";
import MenuItemRow from "@/components/menuItemRow";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from '@/components/Text';
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiDeleteMemberDiscussionGeneral, apiGetDiscussionGeneralOne } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { Feather, MaterialCommunityIcons } from "@expo/vector-icons";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, ToastAndroid, View } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   idUser: string,
   name: string,
   img: string
}

export default function MemberDiscussionDetail() {
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   const { id } = useLocalSearchParams<{ id: string }>()
   const [data, setData] = useState<Props[]>([])
   const [isModal, setModal] = useState(false)
   const [chooseUser, setChooseUser] = useState({ idUser: '', name: '', img: '' })
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   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 apiGetDiscussionGeneralOne({ id: id, user: hasil, cat: 'anggota' })
         setData(response.data)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

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


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

   async function handleDeleteUser() {
      try {
         const hasil = await decryptToken(String(token?.current))
         await apiDeleteMemberDiscussionGeneral({ user: hasil, idUser: chooseUser.idUser }, id)
         ToastAndroid.show("Berhasil mengeluarkan anggota dari diskusi", ToastAndroid.SHORT)
         handleLoad(false)
      } catch (error) {
         console.error(error)
      } finally {
         setModal(false)
      }
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Anggota Diskusi',
               headerTitleAlign: 'center',
            }}
         />
         <ScrollView>
            <View style={[Styles.p15]}>
               <Text style={[Styles.textDefault, Styles.mv05]}>{data.length} Anggota</Text>
               <View style={[Styles.wrapPaper, Styles.mb100]}>
                  {
                     entityUser.role != "user" && entityUser.role != "coadmin" &&
                     <BorderBottomItem
                        onPress={() => { router.push(`/discussion/add-member/${id}`) }}
                        borderType="none"
                        icon={
                           <View style={[Styles.iconContent, ColorsStatus.gray]}>
                              <Feather name="user-plus" size={25} color={'#384288'} />
                           </View>
                        }
                        title="Tambah Anggota"
                     />
                  }
                  {
                     loading ?
                        arrSkeleton.map((item, index) => {
                           return (
                              <SkeletonTwoItem key={index} />
                           )
                        })
                        :
                        data.map((item, index) => {
                           return (
                              <BorderBottomItem
                                 key={index}
                                 borderType="bottom"
                                 icon={
                                    <ImageUser src={`https://wibu-storage.wibudev.com/api/files/${item.img}`} size="sm" />
                                 }
                                 title={item.name}
                                 onPress={() => {
                                    setChooseUser(item)
                                    setModal(true)
                                 }}
                              />
                           )
                        })
                  }
               </View>
            </View>
         </ScrollView>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title={chooseUser.name}>
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="account-eye" color="black" size={25} />}
                  title="Lihat Profil"
                  onPress={() => {
                     setModal(false)
                     router.push(`/member/${chooseUser.idUser}`)
                  }}
               />

               <MenuItemRow
                  icon={<MaterialCommunityIcons name="account-remove" color="black" size={25} />}
                  title="Keluarkan"
                  onPress={() => {
                     setModal(false)
                     AlertKonfirmasi({
                        title: 'Konfirmasi',
                        desc: 'Apakah Anda yakin ingin mengeluarkan anggota?',
                        onPress: () => {
                           handleDeleteUser()
                        }
                     })

                  }}
               />
            </View>
         </DrawerBottom>
      </SafeAreaView>
   )
}