import Styles from "@/constants/Styles";
import { apiDeleteTaskMember, apiGetTaskOne } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Text, ToastAndroid, View } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import AlertKonfirmasi from "../alertKonfirmasi";
import BorderBottomItem from "../borderBottomItem";
import DrawerBottom from "../drawerBottom";
import ImageUser from "../imageNew";
import MenuItemRow from "../menuItemRow";
import SkeletonTwoItem from "../skeletonTwoItem";

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

export default function SectionMemberTask() {
   const [isModal, setModal] = useState(false);
   const { token, decryptToken } = useAuthSession();
   const { id, detail } = useLocalSearchParams<{ id: string; detail: string }>();
   const [data, setData] = useState<Props[]>([]);
   const dispatch = useDispatch();
   const update = useSelector((state: any) => state.taskUpdate);
   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 apiGetTaskOne({
            id: detail,
            user: hasil,
            cat: "member",
         });
         setData(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

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

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


   async function handleDeleteMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiDeleteTaskMember({
            user: hasil,
            idUser: memberChoose.id,
         }, detail)
         if (response.success) {
            ToastAndroid.show("Berhasil menghapus anggota", ToastAndroid.SHORT);
            dispatch(setUpdateTask({ ...update, member: !update.progress }))
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT);
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show("Gagal menghapus anggota", ToastAndroid.SHORT);
      } finally {
         setModal(false);
      }
   }

   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]}>
               {
                  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={`https://wibu-storage.wibudev.com/api/files/${item.img}`}
                                    />
                                 }
                                 title={item.name}
                                 onPress={() => {
                                    setMemberChoose({
                                       id: item.idUser,
                                       name: item.name,
                                    });
                                    setModal(true);
                                 }}
                              />
                           );
                        })
                     ) : (
                        <Text
                           style={[
                              Styles.textDefault,
                              Styles.cGray,
                              { textAlign: "center" },
                           ]}
                        >
                           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="black"
                        size={25}
                     />
                  }
                  title="Lihat Profil"
                  onPress={() => {
                     setModal(false);
                     router.push(`/member/${memberChoose.id}`);
                  }}
               />

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