import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiCreateBanner } from "@/lib/api";
import { addEntity } 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, Text, View } from "react-native";
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 pickImageAsync = async () => {
      let result = await ImagePicker.launchImageLibraryAsync({
         mediaTypes: ['images'],
         allowsEditing: false,
         quality: 1,
      });

      if (!result.canceled) {
         setSelectedImage(result.assets[0].uri);
         setImgForm(result.assets[0])
      } else {
         alert('Tidak ada gambar yang dipilih');
      }
   };


   const handleCreateEntity = async () => {
      const hasil = await decryptToken(String(token?.current))
      const fd = new FormData()
      fd.append("file", JSON.stringify({
         uri: imgForm.uri,
         type: 'image/jpeg', // or response.assets[0].type
         name: imgForm.fileName,
       }))
      fd.append("data", JSON.stringify(
         {
            title: title,
            user: hasil
         }
      ))
      const createdEntity = await apiCreateBanner(fd);
      dispatch(addEntity(createdEntity));
   };

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Tambah Banner',
               headerTitleAlign: 'center',
               headerRight: () => <ButtonSaveHeader 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={setTitle} />
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}