import AppHeader from "@/components/AppHeader";
import ImageUser from "@/components/imageNew";
import LabelStatus from "@/components/labelStatus";
import HeaderRightMemberDetail from "@/components/member/headerMemberDetail";
import Skeleton from "@/components/skeleton";
import Text from "@/components/Text";
import { assetUserImage } from "@/constants/AssetsError";
import { ConstEnv } from "@/constants/ConstEnv";
import { valueRoleUser } from "@/constants/RoleUser";
import Styles from "@/constants/Styles";
import { apiGetProfile } from "@/lib/api";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { router, Stack, useLocalSearchParams } from "expo-router";
import React, { useEffect, useState } from "react";
import { Pressable, RefreshControl, SafeAreaView, ScrollView, View } from "react-native";
import ImageViewing from 'react-native-image-viewing';
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,
   isApprover: boolean,
   role: string
}

export default function MemberDetail() {
   const { id } = useLocalSearchParams<{ id: string }>();
   const { colors } = useTheme();
   const [data, setData] = useState<Props>()
   const [errorImg, setErrorImg] = 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)
   const [preview, setPreview] = 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 : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengambil data"

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


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


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

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               headerTitle: 'Anggota',
               headerTitleAlign: 'center',
               header: () => (
                  <AppHeader title="Anggota"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        (entityUser.role != "user") && isEdit ? <HeaderRightMemberDetail active={data?.isActive} id={id} isApprover={data?.isApprover ?? false} /> : <></>
                     }
                  />
               )
            }}
         />
         <ScrollView
            style={[Styles.h100, { backgroundColor: colors.background }]}
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
                  tintColor={colors.icon}
               />
            }
         >
            <LinearGradient
               colors={[colors.header, colors.homeGradient]}
               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} />
                  </>
               ) : (
                  <>
                     <Pressable onPress={() => setPreview(true)}>
                        <View style={[Styles.memberAvatarRing]}>
                           <ImageUser src={`${ConstEnv.url_storage}/files/${data?.img}`} size="lg" onError={setErrorImg} />
                        </View>
                     </Pressable>
                     <Text style={[Styles.textSubtitle, Styles.cWhite, Styles.mt10, Styles.textCenter]}>{data?.name}</Text>
                     <Text style={[Styles.textMediumNormal, Styles.cWhiteDimmed]}>{data?.role}</Text>
                     <View style={[Styles.memberBadgeRow]}>
                        {data?.isApprover && (
                           <View style={[Styles.memberBadgeApprover]}>
                              <Text style={[Styles.textSmallSemiBold, Styles.cWhite]}>APPROVER</Text>
                           </View>
                        )}
                        <View style={[Styles.memberBadgePill, { backgroundColor: data?.isActive ? colors.success : colors.error }]}>
                           <Text style={[Styles.textSmallSemiBold, Styles.cWhite]}>{data?.isActive ? 'AKTIF' : 'TIDAK AKTIF'}</Text>
                        </View>
                     </View>
                  </>
               )}
            </LinearGradient>

            <View style={[Styles.p15]}>
               <Text style={[Styles.textDefaultSemiBold, Styles.mb08, { color: colors.dimmed }]}>Informasi</Text>
               <View>
                  {loading ? (
                     arrSkeleton.map((_, index) => (
                        <View key={index} style={[Styles.pv14, { borderBottomWidth: index < arrSkeleton.length - 1 ? 1 : 0, borderBottomColor: `${colors.dimmed}30` }]}>
                           <Skeleton width={80} height={8} borderRadius={4} />
                           <View style={[Styles.mt05]}>
                              <Skeleton width={60} widthType="percent" height={10} borderRadius={4} />
                           </View>
                        </View>
                     ))
                  ) : (
                     [
                        { icon: <MaterialCommunityIcons name="card-account-details" size={20} color={colors.icon} />, label: 'NIK', value: data?.nik },
                        { icon: <MaterialCommunityIcons name="office-building-outline" size={20} color={colors.icon} />, label: 'Lembaga Desa', value: data?.group },
                        { icon: <MaterialCommunityIcons name="account-tie" size={20} color={colors.icon} />, label: 'Jabatan', value: data?.position },
                        { icon: <MaterialIcons name="phone" size={20} color={colors.icon} />, label: 'No Telepon', value: `+62${data?.phone}` },
                        { icon: <MaterialIcons name="email" size={20} color={colors.icon} />, label: 'Email', value: data?.email },
                        { icon: <MaterialCommunityIcons name="gender-male-female" size={20} color={colors.icon} />, label: 'Jenis Kelamin', value: data?.gender == "F" ? "Perempuan" : "Laki-Laki" },
                     ].map((item, index, arr) => (
                        <View
                           key={index}
                           style={[Styles.memberInfoRow, { borderBottomWidth: index < arr.length - 1 ? 1 : 0, borderBottomColor: `${colors.dimmed}30` }]}
                        >
                           <View style={[Styles.memberInfoIcon]}>
                              {item.icon}
                           </View>
                           <View style={[Styles.memberInfoContent]}>
                              <Text style={[Styles.textInformation, { color: colors.dimmed }]}>{item.label}</Text>
                              <Text style={[Styles.textDefault, Styles.mt02, { color: colors.text }]} numberOfLines={1}>{item.value ?? '-'}</Text>
                           </View>
                        </View>
                     ))
                  )}
               </View>
            </View>
         </ScrollView>

         <ImageViewing
            images={[{ uri: errorImg ? assetUserImage.uri : `${ConstEnv.url_storage}/files/${data?.img}` }]}
            imageIndex={0}
            visible={preview}
            onRequestClose={() => setPreview(false)}
            doubleTapToZoomEnabled
         />
      </SafeAreaView>
   )
}