import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { apiCreateBanner, apiGetBanner } from "@/lib/api";
import { setEntities } from "@/lib/bannerSlice";
import { useAuthSession } from "@/providers/AuthProvider";
import { Entypo } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import { router, Stack } from "expo-router";
import { 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 CreateBanner() {
   const { decryptToken, token } = useAuthSession();
   const dispatch = useDispatch();
   const [selectedImage, setSelectedImage] = useState<string | undefined>(
      undefined
   );
   const [imgForm, setImgForm] = useState<any>();
   const [title, setTitle] = useState("");
   const [error, setError] = useState(false);
   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) {
         if (result.assets?.[0].uri) {
            setSelectedImage(result.assets[0].uri);
            setImgForm(result.assets[0]);
         } else {
            alert("Tidak ada gambar yang dipilih");
         }
      }
   };

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

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

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

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

         const createdEntity = await apiCreateBanner(fd);
         if (createdEntity.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
            apiGetBanner({ user: hasil }).then((data) =>
               dispatch(setEntities(data.data))
            );
            router.back();
         } else {
            Toast.show({ type: 'small', text1: 'Gagal menambahkan data', })
         }
      } catch (error) {
         console.error(error);
         Toast.show({ type: 'small', text1: 'Gagal menambahkan data', })
      } finally {
         setLoading(false)
      }
   };

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Tambah Banner",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={title == "" || selectedImage == undefined || error || loading ? true : false}
                     category="create"
                     onPress={() => {
                        handleCreateEntity();
                     }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <View style={[Styles.mb15]}>
                  {selectedImage != undefined ? (
                     <Pressable onPress={pickImageAsync}>
                        <Image
                           src={selectedImage}
                           style={{ resizeMode: "contain", width: "100%", height: 100 }}
                        />
                     </Pressable>
                  ) : (
                     <Pressable
                        onPress={pickImageAsync}
                        style={[Styles.wrapPaper, Styles.contentItemCenter]}
                     >
                        <View
                           style={{ justifyContent: "center", alignItems: "center" }}
                        >
                           <Entypo name="image" size={50} color={"#aeaeae"} />
                           <Text style={[Styles.textInformation, Styles.mt05]}>
                              Mohon unggah gambar dalam resolusi 1535 x 450 pixel untuk
                              memastikan
                           </Text>
                        </View>
                     </Pressable>
                  )}
               </View>
               <InputForm
                  label="Judul"
                  type="default"
                  placeholder="Judul"
                  required
                  bg="white"
                  onChange={onValidate}
                  error={error}
                  errorText="Judul harus diisi"
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
