import AlertKonfirmasi from "@/components/alertKonfirmasi";
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 { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Ionicons } from "@expo/vector-icons";
import { router, Stack } from "expo-router";
import { useState } from "react";
import { Image, Modal, Pressable, SafeAreaView, ScrollView, TouchableOpacity, View } from "react-native";
import ImageViewing from 'react-native-image-viewing';
import { useSelector } from 'react-redux';

export default function Profile() {
   const { signOut } = useAuthSession()
   const { theme, setTheme, colors } = useTheme();
   const entities = useSelector((state: any) => state.entities)
   const [error, setError] = useState(false)
   const [preview, setPreview] = useState(false)
   const [showThemeModal, setShowThemeModal] = useState(false)

   const ThemeOption = ({ label, value, icon }: { label: string, value: 'light' | 'dark' | 'system', icon: string }) => (
      <TouchableOpacity
         style={[Styles.itemSelectModal, { backgroundColor: theme === value ? colors.primary + '10' : 'transparent', borderColor: colors.icon + '20' }]}
         onPress={() => {
            setTheme(value);
            setShowThemeModal(false);
         }}
      >
         <View style={Styles.rowItemsCenter}>
            <Ionicons name={icon as any} size={20} color={theme === value ? colors.primary : colors.text} style={{ marginRight: 10 }} />
            <Text style={{ color: colors.text, fontWeight: theme === value ? 'bold' : 'normal' }}>{label}</Text>
         </View>
         {theme === value && <Ionicons name="checkmark" size={20} color={colors.primary} />}
      </TouchableOpacity>
   );

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               headerTitle: 'Profile',
               headerTitleAlign: 'center',
               header: () => (
                  <AppHeader
                     title="Profile"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonHeader
                           item={<AntDesign name="logout" size={20} color="white" />}
                           onPress={() => {
                              AlertKonfirmasi({
                                 title: 'Keluar',
                                 desc: 'Apakah anda yakin ingin keluar?',
                                 onPress: () => { signOut() }
                              })
                           }}
                        />
                     }
                  />
               )
            }}
         />
         <ScrollView style={[Styles.h100, { backgroundColor: colors.background }]}>
            <View style={{ flexDirection: 'column' }}>
               <View style={[Styles.wrapHeadViewMember, { backgroundColor: colors.primary }]}>
                  <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>
               </View>
               <View style={[Styles.p15]}>
                  <View style={[Styles.rowSpaceBetween, Styles.mb15]}>
                     <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>Tampilan</Text>
                  </View>

                  <TouchableOpacity
                     onPress={() => setShowThemeModal(true)}
                     style={[Styles.wrapItemBorderAll, { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderColor: colors.icon + '40', backgroundColor: colors.background }]}
                  >
                     <View style={Styles.rowItemsCenter}>
                        <Ionicons name="color-palette-outline" size={20} color={colors.text} style={{ marginRight: 10 }} />
                        <Text style={{ color: colors.text }}>Tema Aplikasi</Text>
                     </View>
                     <View style={Styles.rowItemsCenter}>
                        <Text style={{ color: colors.icon, marginRight: 5, fontSize: 13 }}>
                           {theme === 'light' ? 'Terang' : theme === 'dark' ? 'Gelap' : 'Sistem'}
                        </Text>
                        <Ionicons name="chevron-forward" size={16} color={colors.icon} />
                     </View>
                  </TouchableOpacity>

                  <View style={[Styles.rowSpaceBetween, Styles.mt15]}>
                     <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>Informasi</Text>
                     {
                        entities.idUserRole != "developer" && <Text onPress={() => { router.push('/edit-profile') }} style={[Styles.textLink]}>Edit</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>

         <Modal
            animationType="fade"
            transparent={true}
            visible={showThemeModal}
            onRequestClose={() => setShowThemeModal(false)}
         >
            <TouchableOpacity style={Styles.modalBgTransparant} activeOpacity={1} onPress={() => setShowThemeModal(false)}>
               <View style={[Styles.modalContent, { backgroundColor: colors.background }]}>
                  <View style={[Styles.titleContainer, { backgroundColor: colors.background, borderBottomColor: colors.icon + '20', borderBottomWidth: 1 }]}>
                     <Text style={[Styles.textSubtitle, { color: colors.text }]}>Pilih Tema</Text>
                     <TouchableOpacity onPress={() => setShowThemeModal(false)}>
                        <Ionicons name="close" size={24} color={colors.text} />
                     </TouchableOpacity>
                  </View>
                  <View style={{ padding: 10 }}>
                     <ThemeOption label="Terang" value="light" icon="sunny-outline" />
                     <ThemeOption label="Gelap" value="dark" icon="moon-outline" />
                     <ThemeOption label="Sistem" value="system" icon="phone-portrait-outline" />
                  </View>
               </View>
            </TouchableOpacity>
         </Modal>

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