import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiDeleteProjectMember, apiGetProjectOne } from "@/lib/api";
import { setUpdateProject } from "@/lib/projectUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";
import ModalConfirmation from "../ModalConfirmation";
import BorderBottomItem from "../borderBottomItem";
import DrawerBottom from "../drawerBottom";
import ImageUser from "../imageNew";
import MenuItemRow from "../menuItemRow";
import SkeletonTwoItem from "../skeletonTwoItem";
import Text from "../Text";

type Props = {
   id: string;
   idUser: string;
   name: string;
   email: string;
   img: string;
   position: string;
};

export default function SectionMember({ status, refreshing }: { status: number | undefined, refreshing?: boolean }) {
   const { colors } = useTheme();
   const dispatch = useDispatch()
   const entityUser = useSelector((state: any) => state.user)
   const update = useSelector((state: any) => state.projectUpdate)
   const [isModal, setModal] = useState(false);
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [selectLink, setSelectLink] = useState<Props | null>(null);
   const [showDeleteModal, setShowDeleteModal] = useState(false);
   const [data, setData] = useState<Props[]>([]);
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 3 })
   const [memberChoose, setMemberChoose] = useState({
      id: '',
      name: '',
   })


   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetProjectOne({
            user: hasil,
            cat: "member",
            id: id,
         });
         setData(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

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

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

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

   async function handleDeleteMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiDeleteProjectMember({
            user: hasil,
            idUser: memberChoose.id,
         }, id)
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menghapus anggota', })
            dispatch(setUpdateProject({ ...update, member: !update.member }))
            setModal(false);
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menghapus anggota"

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

   return (
      <>
         <View style={[Styles.mb15]}>
            <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
               <Text style={[Styles.textDefaultSemiBold]}>Anggota</Text>
               <Text style={[Styles.textDefault]}>Total {data.length} Anggota</Text>
            </View>

            <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.background }]}>
               {
                  loading ?
                     arrSkeleton.map((item, index) => {
                        return (
                           <SkeletonTwoItem key={index} />
                        )
                     })
                     :
                     data.length > 0
                        ?
                        data.map((item, index) => {
                           return (
                              <BorderBottomItem
                                 key={index}
                                 borderType="bottom"
                                 icon={<ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} />}
                                 title={item.name}
                                 onPress={() => {
                                    if (status == 3) return
                                    setMemberChoose({
                                       id: item.idUser,
                                       name: item.name,
                                    })
                                    setModal(true);
                                 }}
                              />
                           );
                        })
                        :
                        <Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada anggota</Text>
               }
            </View>
         </View>

         <DrawerBottom
            animation="slide"
            isVisible={isModal}
            setVisible={setModal}
            title={memberChoose.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/${memberChoose.id}`);
                  }}
               />
               {
                  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)
               handleDeleteMember()
            }}
            onCancel={() => setShowDeleteModal(false)}
            confirmText="Keluarkan"
            cancelText="Batal"
         />
      </>
   );
}
