import ModalConfirmation from "@/components/ModalConfirmation"
import AppHeader from "@/components/AppHeader"
import BorderBottomItem from "@/components/borderBottomItem"
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 { useTheme } from "@/providers/ThemeProvider"
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 { colors } = useTheme()
   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
   })
   const [showDeleteModal, setShowDeleteModal] = useState(false)

   function handleMemberOut() {
      setModal(false)
      setTimeout(() => {
         setShowDeleteModal(true)
      }, 600)
   }

   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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengeluarkan anggota"

         Toast.show({ type: 'small', text1: message })
      } 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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengubah status admin"

         Toast.show({ type: 'small', text1: message })
      } 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 style={{ flex: 1, backgroundColor: colors.background }}>
         <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} />,
               header: () => (
                  <AppHeader
                     title="Informasi Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision) && <HeaderRightDivisionInfo id={id} active={dataDetail?.isActive} />
                     }
                  />
               )
            }}
         />
         <ScrollView
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
                  tintColor={colors.icon}
               />
            }
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <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, Styles.noShadow, { backgroundColor: colors.card, borderWidth: 1, borderColor: colors.icon + '20' }]}>
                     {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, Styles.noShadow, { backgroundColor: colors.card, borderWidth: 1, borderColor: colors.icon + '20' }]}>
                     {
                        ((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision) &&
                        dataDetail?.isActive && (
                           <BorderBottomItem
                              onPress={() => { router.push(`/division/${id}/add-member`) }}
                              borderType="none"
                              icon={
                                 <View style={[Styles.iconContent]}>
                                    <Feather name="user-plus" size={25} color={'black'} />
                                 </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]}>
                        <MaterialIcons name="verified-user" size={25} color={'black'} />
                     </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={colors.primary} />
                     </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>

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