import AlertKonfirmasi from "@/components/alertKonfirmasi"
import BorderBottomItem from "@/components/borderBottomItem"
import ButtonBackHeader from "@/components/buttonBackHeader"
import HeaderRightDivisionInfo from "@/components/division/headerDivisionInfo"
import DrawerBottom from "@/components/drawerBottom"
import ImageUser from "@/components/imageNew"
import SectionCancel from "@/components/sectionCancel"
import Skeleton from "@/components/skeleton"
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 { apiDeleteMemberDivision, apiGetDivisionOneDetail, apiGetDivisionOneFeature, apiUpdateStatusAdminDivision } from "@/lib/api"
import { useAuthSession } from "@/providers/AuthProvider"
import { Feather, MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons"
import { router, Stack, useLocalSearchParams } from "expo-router"
import { useEffect, useState } from "react"
import { Pressable, RefreshControl, SafeAreaView, ScrollView, View } from "react-native"
import Toast from "react-native-toast-message"
import { useSelector } from "react-redux"

type PropsDetail = {
   id: string,
   idVillage: string,
   idGroup: string,
   name: string,
   desc: string,
   isActive: boolean,
}

type PropsMember = {
   id: string,
   isAdmin: boolean,
   isLeader: boolean,
   idUser: string,
   name: string,
   img: string
}

export default function InformationDivision() {
   const [refreshing, setRefreshing] = useState(false)
   const entityUser = useSelector((state: any) => state.user)
   const { id } = useLocalSearchParams<{ id: string }>()
   const [isModal, setModal] = useState(false)
   const { token, decryptToken } = useAuthSession()
   const [dataDetail, setDataDetail] = useState<PropsDetail>()
   const [dataMember, setDataMember] = useState<PropsMember[]>([])
   const [refresh, setRefresh] = useState(false)
   const update = useSelector((state: any) => state.divisionUpdate)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)
   const [loading, setLoading] = useState(true)
   const [isMemberDivision, setIsMemberDivision] = useState(false)
   const [isAdminDivision, setIsAdminDivision] = useState(false)
   const [dataMemberChoose, setDataMemberChoose] = useState({
      id: '',
      name: '',
      isAdmin: false
   })

   function handleMemberOut() {
      setModal(false)
      AlertKonfirmasi({
         title: 'Konfirmasi',
         desc: 'Apakah anda yakin ingin mengeluarkan anggota?',
         onPress: () => { memberOut() }
      })
   }

   async function memberOut() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteMemberDivision({ user: hasil, id: dataMemberChoose.id }, id)
         if (response.success) {
            setRefresh(!refresh)
            Toast.show({ type: 'small', text1: 'Berhasil mengeluarkan anggota', })
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setModal(false)
      }
   }

   async function handleMemberAdmin() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiUpdateStatusAdminDivision({ user: hasil, id: dataMemberChoose.id, isAdmin: dataMemberChoose.isAdmin }, id)
         if (response.success) {
            setRefresh(!refresh)
            Toast.show({ type: 'small', text1: dataMemberChoose.isAdmin ? 'Berhasil memberhentikan admin' : 'Berhasil menjadi admin', })
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setModal(false)
      }
   }

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDivisionOneDetail({ user: hasil, id })
         setDataDetail(response.data.division)
         setDataMember(response.data.member)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

   const handleRefresh = async () => {
      setRefreshing(true)
      handleLoad(false)
      handleCheckMember()
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   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);
      }
   }

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

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

   function handleChooseMember(item: PropsMember) {
      setDataMemberChoose(item)
      setModal(true)
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Informasi Divisi',
               headerTitleAlign: 'center',
               headerRight: () => ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision) && <HeaderRightDivisionInfo id={id} active={dataDetail?.isActive} />,
            }}
         />
         <ScrollView
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
               />
            }
            style={[Styles.h100]}
         >
            <View style={[Styles.p15]}>
               {
                  dataDetail?.isActive == false && (
                     <SectionCancel title={'Divisi nonaktif'} />
                  )
               }
               <View style={[Styles.mb15]}>
                  <Text style={[Styles.textDefaultSemiBold, Styles.mb05]}>Deskripsi Divisi</Text>
                  <View style={[Styles.wrapPaper]}>
                     {loading ?
                        arrSkeleton.map((item, index) => {
                           return (
                              <Skeleton key={index} width={100} height={10} widthType="percent" borderRadius={10} />
                           )
                        })
                        :
                        <Text>{dataDetail?.desc}</Text>
                     }
                  </View>
               </View>
               <View style={[Styles.mb15]}>
                  <Text style={[Styles.textDefault, Styles.mv05]}>{dataMember.length} Anggota</Text>
                  <View style={[Styles.wrapPaper]}>
                     {
                        ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision) &&
                        dataDetail?.isActive && (
                           <BorderBottomItem
                              onPress={() => { router.push(`/division/${id}/add-member`) }}
                              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} />
                              )
                           })
                           :
                           dataMember.map((item, index) => {
                              return (
                                 <BorderBottomItem
                                    key={index}
                                    borderType="bottom"
                                    onPress={() => { dataDetail?.isActive && (isAdminDivision || (entityUser.role != "user" && entityUser.role != "coadmin")) && handleChooseMember(item) }}
                                    icon={
                                       <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="sm" />
                                    }
                                    title={item.name}
                                    rightTopInfo={item.isAdmin ? "Admin" : "Anggota"}
                                 />
                              )
                           })
                     }
                  </View>
               </View>
            </View>
         </ScrollView>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title={dataMemberChoose.name}>
            <View>
               <Pressable style={[Styles.wrapItemBorderBottom]} onPress={() => { handleMemberAdmin() }}>
                  <View style={[Styles.rowItemsCenter]}>
                     <View style={[Styles.iconContent, ColorsStatus.info]}>
                        <MaterialIcons name="verified-user" size={25} color='#19345E' />
                     </View>
                     <View style={[Styles.rowSpaceBetween, { width: '88%' }]}>
                        <View style={[Styles.ml10]}>
                           <Text style={[Styles.textDefault]}>{dataMemberChoose.isAdmin ? 'Memberhentikan sebagai admin' : 'Jadikan admin'}</Text>
                        </View>
                     </View>
                  </View>
               </Pressable>

               <Pressable style={[Styles.wrapItemBorderBottom]} onPress={() => { handleMemberOut() }}>
                  <View style={[Styles.rowItemsCenter]}>
                     <View style={[Styles.iconContent, ColorsStatus.info]}>
                        <MaterialCommunityIcons name="close-circle" size={25} color='#19345E' />
                     </View>
                     <View style={[Styles.rowSpaceBetween, { width: '88%' }]}>
                        <View style={[Styles.ml10]}>
                           <Text style={[Styles.textDefault]}>Keluarkan dari divisi</Text>
                        </View>
                     </View>
                  </View>
               </Pressable>
            </View>
         </DrawerBottom>
      </SafeAreaView>
   )
}