import AppHeader from "@/components/AppHeader";
import { ButtonHeader } from "@/components/buttonHeader";
import Text from "@/components/Text";
import { assetUserImage } from "@/constants/AssetsError";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetProfile } from "@/lib/api";
import { setEntities } from "@/lib/entitiesSlice";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Feather, MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { router, Stack } from "expo-router";
import { useState } from "react";
import { Image, Pressable, RefreshControl, SafeAreaView, ScrollView, View } from "react-native";
import ImageViewing from 'react-native-image-viewing';
import { useDispatch, useSelector } from 'react-redux';

export default function Profile() {
   const { colors } = useTheme();
   const entities = useSelector((state: any) => state.entities)
   const [error, setError] = useState(false)
   const [preview, setPreview] = useState(false)
   const [refreshing, setRefreshing] = useState(false)
   const dispatch = useDispatch()
   const { token, decryptToken } = useAuthSession()

   async function handleUserLogin() {
      const hasil = await decryptToken(String(token?.current))
      apiGetProfile({ id: hasil })
         .then((data) => dispatch(setEntities(data.data)))
         .catch((error) => {
            console.error(error)
         });
   }

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

   const infoRows = [
      { icon: <MaterialCommunityIcons name="card-account-details" size={20} color={colors.icon} />, label: 'NIK', value: entities.nik },
      { icon: <MaterialCommunityIcons name="office-building-outline" size={20} color={colors.icon} />, label: 'Lembaga Desa', value: entities.group },
      { icon: <MaterialCommunityIcons name="account-tie" size={20} color={colors.icon} />, label: 'Jabatan', value: entities.position },
      { icon: <MaterialIcons name="phone" size={20} color={colors.icon} />, label: 'No Telepon', value: `0${entities.phone}` },
      { icon: <MaterialIcons name="email" size={20} color={colors.icon} />, label: 'Email', value: entities.email },
      { icon: <MaterialCommunityIcons name="gender-male-female" size={20} color={colors.icon} />, label: 'Jenis Kelamin', value: entities.gender == "F" ? 'Perempuan' : 'Laki-laki' },
   ]

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               headerTitle: 'Profile',
               headerTitleAlign: 'center',
               header: () => (
                  <AppHeader
                     title="Profile"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonHeader
                           item={<Feather name="settings" size={20} color="white" />}
                           onPress={() => router.push('/setting')}
                        />
                     }
                  />
               )
            }}
         />
         <ScrollView
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
                  tintColor={colors.icon}
               />
            }
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <LinearGradient
               colors={[colors.header, colors.homeGradient]}
               style={[Styles.wrapHeadViewMember]}
            >
               <Pressable onPress={() => setPreview(true)}>
                  <View style={[Styles.memberAvatarRing]}>
                     <Image
                        source={error ? require("../../assets/images/user.jpg") : { uri: `${ConstEnv.url_storage}/files/${entities.img}` }}
                        onError={() => setError(true)}
                        style={[Styles.userProfileBig]}
                     />
                  </View>
               </Pressable>
               <Text style={[Styles.textSubtitle, Styles.cWhite, Styles.mt10, Styles.textCenter]}>{entities.name}</Text>
               <Text style={[Styles.textMediumNormal, Styles.cWhiteDimmed]}>{entities.role}</Text>
               {entities.isApprover && (
                  <View style={[Styles.memberBadgeRow, { justifyContent: 'center' }]}>
                     <View style={[Styles.memberBadgeApprover]}>
                        <Text style={[Styles.textSmallSemiBold, Styles.cWhite]}>APPROVER</Text>
                     </View>
                  </View>
               )}
            </LinearGradient>

            <View style={[Styles.p15]}>
               <Text style={[Styles.textDefaultSemiBold, Styles.mb08, { color: colors.dimmed }]}>Informasi</Text>
               <View>
                  {infoRows.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: error ? assetUserImage.uri : `${ConstEnv.url_storage}/files/${entities.img}` }]}
            imageIndex={0}
            visible={preview}
            onRequestClose={() => setPreview(false)}
            doubleTapToZoomEnabled
         />
      </SafeAreaView>
   )
}
