import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import LoadingCenter from "@/components/loadingCenter";
import Text from "@/components/Text";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiEditBanner, apiGetBanner, apiGetBannerOne } from "@/lib/api";
import { setEntities } from "@/lib/bannerSlice";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Entypo } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import {
   Image,
   Pressable,
   SafeAreaView,
   ScrollView,
   View
} from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch } from "react-redux";

export default function EditBanner() {
   const dispatch = useDispatch();
   const { decryptToken, token } = useAuthSession();
   const { colors } = useTheme();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [selectedImage, setSelectedImage] = useState<
      string | undefined | { uri: string }
   >(undefined);
   const [title, setTitle] = useState("");
   const [error, setError] = useState(false);
   const [imgForm, setImgForm] = useState<any>();
   const [loading, setLoading] = useState(false)

   const pickImageAsync = async () => {
      let result = await ImagePicker.launchImageLibraryAsync({
         mediaTypes: ["images"],
         allowsEditing: false,
         quality: 1,
         aspect: [1535, 450],
      });

      if (!result.canceled) {
         setSelectedImage(result.assets[0].uri);
         setImgForm(result.assets[0]);
      }
   };

   const handleLoadData = async () => {
      const hasil = await decryptToken(String(token?.current));
      const data = await apiGetBannerOne({ user: hasil, id });
      setSelectedImage({
         uri: `${ConstEnv.url_storage}/files/${data.data.image}`,
      });
      setTitle(data.data.title);
   };

   useEffect(() => {
      handleLoadData();
   }, []);

   function onValidate(val: string) {
      setTitle(val);
      if (val == "") {
         setError(true);
      } else {
         setError(false);
      }
   }

   const handleUpdateEntity = async () => {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current));
         const fd = new FormData();

         if (imgForm != undefined) {
            fd.append("file", {
               uri: imgForm.uri,
               type: imgForm.mimeType,
               name: imgForm.fileName,
            } as any);
         } else {
            fd.append("file", "undefined",);
         }

         fd.append(
            "data",
            JSON.stringify({
               title,
               user: hasil,
            })
         );

         const updatedEntity = await apiEditBanner(fd, id)
         if (updatedEntity.success) {
            Toast.show({ type: 'small', text1: 'Berhasil mengupdate data', })
            apiGetBanner({ user: hasil }).then((data) =>
               dispatch(setEntities(data.data))
            );
            router.back();
         } else {
            Toast.show({ type: 'small', text1: 'Gagal mengupdate data', })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengupdate data"

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

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Edit Banner",
               headerTitleAlign: "center",
               // headerRight: () => <ButtonSaveHeader
               //    disable={title == "" || error || loading ? true : false}
               //    onPress={() => { handleUpdateEntity() }}
               //    category="update" />,
               header: () => (
                  <AppHeader
                     title="Edit Banner"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={title == "" || error || loading ? true : false}
                           onPress={() => { handleUpdateEntity() }}
                           category="update" />
                     }
                  />
               )
            }}
         />
         {loading && <LoadingCenter />}
         <ScrollView showsVerticalScrollIndicator={false} style={[Styles.h100, { backgroundColor: colors.background }]}>
            <View style={[Styles.p15, Styles.mb100]}>
               <View style={[Styles.mb15]}>
                  {selectedImage != undefined ? (
                     <Pressable onPress={pickImageAsync}>
                        <Image
                           src={
                              typeof selectedImage === "string"
                                 ? selectedImage
                                 : selectedImage.uri
                           }
                           style={[Styles.resizeContain, Styles.w100, { height: 100 }]}
                        />
                     </Pressable>
                  ) : (
                     <Pressable
                        onPress={pickImageAsync}
                        style={[Styles.wrapPaper, Styles.contentItemCenter]}
                     >
                        <View
                           style={[Styles.contentItemCenter]}
                        >
                           <Entypo name="image" size={50} color={"#aeaeae"} />
                           <Text style={[Styles.textInformation, Styles.mt05]}>
                              Mohon unggah gambar dalam resolusi 1650 x 720 pixel untuk
                              memastikan
                           </Text>
                        </View>
                     </Pressable>
                  )}
               </View>
               <InputForm
                  label="Judul"
                  type="default"
                  placeholder="Judul"
                  required
                  bg={colors.card}
                  value={title}
                  error={error}
                  onChange={onValidate}
                  errorText="Judul tidak boleh kosong"
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
