import AppHeader from "@/components/AppHeader";
import { ButtonHeader } from "@/components/buttonHeader";
import ItemDetailMember from "@/components/itemDetailMember";
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 } 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)
   };

   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 }]}
         >
            <View style={[Styles.flexColumn]}>
               <LinearGradient
                  colors={[colors.header, colors.homeGradient]}
                  style={[Styles.wrapHeadViewMember]}
               >
                  <Pressable onPress={() => setPreview(true)}>
                     <Image
                        source={error ? require("../../assets/images/user.jpg") : { uri: `${ConstEnv.url_storage}/files/${entities.img}` }}
                        onError={() => { setError(true) }}
                        style={[Styles.userProfileBig]}
                     />
                  </Pressable>
                  <Text style={[Styles.textSubtitle, Styles.cWhite, Styles.mt10]}>{entities.name}</Text>
                  <Text style={[Styles.textMediumNormal, Styles.cWhite]}>{entities.role}</Text>
               </LinearGradient>
               <View style={[Styles.p15]}>
                  <View style={[Styles.rowSpaceBetween]}>
                     <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>Informasi</Text>
                  </View>
                  {/* Note: ItemDetailMember might need updates to support dynamic colors if it uses default text colors */}
                  <ItemDetailMember category="nik" value={entities.nik} />
                  <ItemDetailMember category="group" value={entities.group} />
                  <ItemDetailMember category="position" value={entities.position} />
                  <ItemDetailMember category="phone" value={`0${entities.phone}`} />
                  <ItemDetailMember category="email" value={entities.email} />
                  <ItemDetailMember category="gender" value={entities.gender == "F" ? 'Perempuan' : 'Laki-laki'} />
               </View>
            </View>
         </ScrollView>

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