import AppHeader from "@/components/AppHeader";
import BorderBottomItem from "@/components/borderBottomItem";
import DrawerBottom from "@/components/drawerBottom";
import ImageUser from "@/components/imageNew";
import MenuItemRow from "@/components/menuItemRow";
import ModalConfirmation from "@/components/ModalConfirmation";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from '@/components/Text';
import { ColorsStatus } from "@/constants/ColorsStatus";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiDeleteMemberDiscussionGeneral, apiGetDiscussionGeneralOne } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Feather, MaterialCommunityIcons } from "@expo/vector-icons";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useSelector } from "react-redux";

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

export default function MemberDiscussionDetail() {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   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)
   const [showDeleteModal, setShowDeleteModal] = useState(false)


   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)
         Toast.show({ type: 'small', text1: 'Berhasil mengeluarkan anggota dari diskusi', })
         handleLoad(false)
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengeluarkan anggota"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setModal(false)
      }
   }

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Anggota Diskusi',
               headerTitleAlign: 'center',
               header: () => (
                  <AppHeader
                     title="Anggota Diskusi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                  />
               )
            }}
         />
         <ScrollView style={[Styles.h100, Styles.flex1, { backgroundColor: colors.background }]}>
            <View style={[Styles.p15]}>
               <Text style={[Styles.textDefault, Styles.mv05]}>{data.length} Anggota</Text>
               <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.background }]}>
                  {
                     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={`${ConstEnv.url_storage}/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={colors.text} size={25} />}
                  title="Lihat Profil"
                  onPress={() => {
                     setModal(false)
                     router.push(`/member/${chooseUser.idUser}`)
                  }}
               />
               {
                  entityUser.role != "user" && entityUser.role != "coadmin" &&
                  <MenuItemRow
                     icon={<MaterialCommunityIcons name="account-remove" color={colors.text} size={25} />}
                     title="Keluarkan"
                     onPress={() => {
                        setModal(false)
                        setTimeout(() => {
                           setShowDeleteModal(true)
                        }, 600)
                     }}
                  />
               }

            </View>
         </DrawerBottom>

         <ModalConfirmation
            visible={showDeleteModal}
            title="Konfirmasi"
            message="Apakah anda yakin ingin mengeluarkan anggota?"
            onConfirm={() => {
               setShowDeleteModal(false)
               handleDeleteUser()
            }}
            onCancel={() => setShowDeleteModal(false)}
            confirmText="Hapus"
            cancelText="Batal"
         />
      </SafeAreaView>
   )
}