import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiDeleteTaskMember, apiGetTaskOne } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
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 { Pressable, View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";
import DrawerBottom from "../drawerBottom";
import ImageUser from "../imageNew";
import MenuItemRow from "../menuItemRow";
import ModalConfirmation from "../ModalConfirmation";
import Skeleton from "../skeleton";
import Text from "../Text";

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

export default function SectionMemberTask({ refreshing, isAdminDivision }: { refreshing: boolean, isAdminDivision: boolean }) {
   const { colors } = useTheme()
   const [isModal, setModal] = useState(false);
   const [selectLink, setSelectLink] = useState<Props | null>(null)
   const [showDeleteModal, setShowDeleteModal] = useState(false)
   const entityUser = useSelector((state: any) => state.user);
   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);
   }, [])

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

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

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

   return (
      <>
         <View style={[Styles.mb15]}>
            <View style={[Styles.rowSpaceBetween, { marginBottom: 5 }]}>
               <Text style={[Styles.textDefaultSemiBold]}>Anggota</Text>
               {!loading && data.length > 0 && (
                  <Text style={[Styles.textDefault, { color: colors.dimmed }]}>{data.length} orang</Text>
               )}
            </View>

            <View style={{ gap: 6 }}>
               {
                  loading ?
                     arrSkeleton.map((item, index) => {
                        return (
                           <View key={index} style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
                              <Skeleton width={40} height={40} borderRadius={20} />
                              <View style={{ flex: 1, gap: 5 }}>
                                 <Skeleton width={60} height={12} widthType="percent" borderRadius={6} />
                                 <Skeleton width={35} height={10} widthType="percent" borderRadius={6} />
                              </View>
                           </View>
                        )
                     })
                     :
                     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={() => {
                              //       setMemberChoose({
                              //          id: item.idUser,
                              //          name: item.name,
                              //       });
                              //       setModal(true);
                              //    }}
                              // />
                              <Pressable
                                 key={index}
                                 onPress={() => {
                                    setMemberChoose({
                                       id: item.idUser,
                                       name: item.name,
                                    });
                                    setModal(true);
                                 }}
                                 style={{
                                    flexDirection: 'row',
                                    alignItems: 'center',
                                    backgroundColor: colors.card,
                                    borderRadius: 10,
                                    borderWidth: 1,
                                    borderColor: colors.icon + '18',
                                    paddingHorizontal: 12,
                                    paddingVertical: 10,
                                    gap: 12,
                                 }}
                              >
                                 <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                                 <View style={{ flex: 1 }}>
                                    <Text style={[Styles.textDefault]} numberOfLines={1}>{item.name}</Text>
                                 </View>
                                 <View style={{
                                    backgroundColor: colors.dimmed + '15',
                                    borderRadius: 20,
                                    paddingHorizontal: 8,
                                    paddingVertical: 3,
                                 }}>
                                    <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed }]} numberOfLines={1}>
                                       {item.position}
                                    </Text>
                                 </View>
                              </Pressable>
                           );
                        })
                     ) : (
                        <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") || isAdminDivision)
                     ?
                     <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"
         />
      </>
   );
}
