import ButtonBackHeader from "@/components/buttonBackHeader";
import ImageUser from "@/components/imageNew";
import ItemDetailMember from "@/components/itemDetailMember";
import LabelStatus from "@/components/labelStatus";
import HeaderRightMemberDetail from "@/components/member/headerMemberDetail";
import Skeleton from "@/components/skeleton";
import Text from "@/components/Text";
import { ConstEnv } from "@/constants/ConstEnv";
import { valueRoleUser } from "@/constants/RoleUser";
import Styles from "@/constants/Styles";
import { apiGetProfile } from "@/lib/api";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { RefreshControl, SafeAreaView, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useSelector } from "react-redux";

type Props = {
   id: string,
   name: string,
   nik: string,
   email: string,
   phone: string,
   gender: string,
   position: string,
   group: string,
   img: string,
   isActive: boolean,
   role: string
}

export default function MemberDetail() {
   const { id } = useLocalSearchParams<{ id: string }>();
   const [data, setData] = useState<Props>()
   const [error, setError] = useState(false)
   const entityUser = useSelector((state: any) => state.user)
   const [isEdit, setEdit] = useState(true)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)
   const [loading, setLoading] = useState(true)
   const [refreshing, setRefreshing] = useState(false)

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const response = await apiGetProfile({ id: id })
         if (response.success) {
            setData(response.data)
            setEdit(valueRoleUser.filter((v) => v.login == entityUser.role)[0]?.data.some((i: any) => i.id == response.data.idUserRole))
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Gagal mengambil data' })
      } finally {
         setLoading(false)
      }
   }


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


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

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Anggota',
               headerTitleAlign: 'center',
               headerRight: () => (entityUser.role != "user") && isEdit ? <HeaderRightMemberDetail active={data?.isActive} id={id} /> : <></>,
               headerShadowVisible: false
            }}
         />
         <ScrollView
            style={[Styles.h100]}
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
               />
            }
         >
            <View style={[Styles.wrapHeadViewMember]}>
               {
                  loading ?
                     <>
                        <Skeleton width={100} height={100} borderRadius={100} />
                        <Skeleton width={200} height={10} borderRadius={5} />
                        <Skeleton width={150} height={10} borderRadius={5} />
                     </>
                     :
                     <>
                        <ImageUser src={`${ConstEnv.url_storage}/files/${data?.img}`} size="lg" />
                        <Text style={[Styles.textSubtitle, Styles.cWhite, Styles.mt10, { textAlign: 'center' }]}>{data?.name}</Text>
                        <Text style={[Styles.textMediumNormal, Styles.cWhite]}>{data?.role}</Text>
                     </>

               }
            </View>
            <View style={[Styles.p15]}>
               <View style={[Styles.rowSpaceBetween]}>
                  <Text style={[Styles.textDefaultSemiBold]}>Informasi</Text>
                  <LabelStatus
                     size="small"
                     category={data?.isActive ? 'success' : 'error'}
                     text={data?.isActive ? 'AKTIF' : 'TIDAK AKTIF'}
                  />
               </View>
               {
                  loading ?
                     arrSkeleton.map((item, index) => {
                        return (
                           <Skeleton key={index} width={100} widthType="percent" height={25} borderRadius={5} />
                        )
                     })
                     :
                     <>
                        <ItemDetailMember category="nik" value={data?.nik} />
                        <ItemDetailMember category="group" value={data?.group} />
                        <ItemDetailMember category="position" value={data?.position} />
                        <ItemDetailMember category="phone" value={`+62${data?.phone}`} />
                        <ItemDetailMember category="email" value={data?.email} />
                        <ItemDetailMember category="gender" value={data?.gender == "F" ? "Perempuan" : "Laki-Laki"} />
                     </>
               }

            </View>
         </ScrollView>
      </SafeAreaView>
   )
}