import AppHeader from "@/components/AppHeader";
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 { 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 { 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,
   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} /> : <></>
                     }
                  />
               )
            }}
         />
         <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)}>
                           <ImageUser src={`${ConstEnv.url_storage}/files/${data?.img}`} size="lg" onError={setErrorImg} />
                        </Pressable>
                        <Text style={[Styles.textSubtitle, Styles.cWhite, Styles.mt10, Styles.textCenter]}>{data?.name}</Text>
                        <Text style={[Styles.textMediumNormal, Styles.cWhite]}>{data?.role}</Text>
                     </>

               }
            </LinearGradient>
            <View style={[Styles.p15]}>
               <View style={[Styles.rowSpaceBetween]}>
                  <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>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>

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