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, Platform, Pressable, SafeAreaView, ScrollView, Text, View } from "react-native";
import { useDispatch } from "react-redux";
import * as FileSystem from 'expo-file-system';
import axios from "axios";
import ReactNativeBlobUtil from 'react-native-blob-util';
import { launchImageLibrary } from "react-native-image-picker";

const debug = true


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 () => {
      kirim()
      return
      let result = await ImagePicker.launchImageLibraryAsync({
         mediaTypes: ['images'],
         allowsEditing: false,
         quality: 1,
      });

      const formData = new FormData()
      formData.append('file', result.assets![0].uri)

      if (debug) console.log("[mengirim gambar]")
      const res = await fetch("http://10.0.2.2:3000/api/v2/test", {
         method: "POST",
         body: formData,

      });

      console.log("[res]", await res.json())

      if (debug) console.log("[pickImageAsync]")

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

            const formData = new FormData()
            formData.append('file', result.assets[0].uri)

            if (debug) console.log("[mengirim gambar]")
            const res = await fetch("http://10.0.2.2:3000/api/v2/test", {
               method: "POST",
               body: formData,

            });

            console.log("[res]", await res.json())

         } else {
            if (debug) console.log("[pickImageAsync]", 'Tidak ada gambar yang dipilih');
            alert('Tidak ada gambar yang dipilih');
         }
         console.log("[imgForm]", imgForm)
      } else {
         if (debug) console.log("[pickImageAsync]", 'Tidak ada gambar yang dipilih');
         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: imgForm.mimeType,
      //    name: imgForm.fileName,
      //    size: imgForm.fileSize,
      // }))
      // fd.append("data", JSON.stringify(
      //    {
      //       title: title,
      //       user: hasil
      //    }
      // ))
      // const createdEntity = await apiCreateBanner(fd);
      // console.log("[createdEntity]", createdEntity)
      // 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>
   )
}

const requestPermission = async () => {
   if (Platform.OS !== 'web') {
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
         alert('Maaf, kami membutuhkan izin untuk mengakses galeri!');
         return false;
      }
      return true;
   }
   return true;
};

const base64ToBlob = (base64: string, mimeType: string) => {
   const byteString = atob(base64);
   const arrayBuffer = new ArrayBuffer(byteString.length);
   const int8Array = new Uint8Array(arrayBuffer);

   for (let i = 0; i < byteString.length; i++) {
     int8Array[i] = byteString.charCodeAt(i);
   }

   return new Blob([int8Array], { type: mimeType });
 };


async function kirim() {
   console.log("clicked");
   const result = await launchImageLibrary({
     mediaType: "photo",
     quality: 1,
     includeBase64: true,
   });

   if (!result.assets || result.assets.length === 0) {
     console.log("No image selected");
     return;
   }

   const base64 = result.assets[0].base64!;
   const mimeType = result.assets[0].type!; // e.g., 'image/jpeg'

   const blob = base64ToBlob(base64, mimeType);

   const formData = new FormData();
   formData.append("file", blob);
   formData.append("name", "bip.png");
   const res = await fetch("http://10.0.2.2:3000/api/v2/test", {
     method: "POST",
     body: formData,
   });
   console.log(await res.text());

}


