import AppHeader from "@/components/AppHeader"
import BorderBottomItem from "@/components/borderBottomItem"
import ButtonSaveHeader from "@/components/buttonSaveHeader"
import ButtonSelect from "@/components/buttonSelect"
import DrawerBottom from "@/components/drawerBottom"
import { InputForm } from "@/components/inputForm"
import LoadingCenter from "@/components/loadingCenter"
import MenuItemRow from "@/components/menuItemRow"
import Text from "@/components/Text"
import Styles from "@/constants/Styles"
import { apiCreateDiscussion } from "@/lib/api"
import { setUpdateDiscussion } from "@/lib/discussionUpdate"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons"
import * as DocumentPicker from "expo-document-picker"
import { router, Stack, useLocalSearchParams } from "expo-router"
import { useState } from "react"
import { SafeAreaView, ScrollView, View } from "react-native"
import Toast from "react-native-toast-message"
import { useDispatch, useSelector } from "react-redux"


export default function CreateDiscussionDivision() {
   const { colors } = useTheme();
   const { id } = useLocalSearchParams<{ id: string }>()
   const [desc, setDesc] = useState('')
   const { token, decryptToken } = useAuthSession()
   const update = useSelector((state: any) => state.discussionUpdate)
   const dispatch = useDispatch();
   const [loading, setLoading] = useState(false)
   const [fileForm, setFileForm] = useState<any[]>([])
   const [isModalFile, setModalFile] = useState(false)
   const [indexDelFile, setIndexDelFile] = useState<number>(0)

   const pickDocumentAsync = async () => {
      let result = await DocumentPicker.getDocumentAsync({
         type: ["*/*"],
         multiple: true
      });
      if (!result.canceled) {
         for (let i = 0; i < result.assets?.length; i++) {
            if (result.assets[i].uri) {
               setFileForm((prev) => [...prev, result.assets[i]])
            }
         }
      }
   };

   function deleteFile(index: number) {
      setFileForm([...fileForm.filter((val, i) => i !== index)])
      setModalFile(false)
   }


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

         for (let i = 0; i < fileForm.length; i++) {
            fd.append(`file${i}`, {
               uri: fileForm[i].uri,
               type: 'application/octet-stream',
               name: fileForm[i].name,
            } as any);
         }

         fd.append("data", JSON.stringify(
            { user: hasil, desc, idDivision: id }
         ))

         const response = await apiCreateDiscussion(fd)

         // const response = await apiCreateDiscussion({ data: { user: hasil, desc, idDivision: id } })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
            dispatch(setUpdateDiscussion({ ...update, data: !update.data }));
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menambahkan data"

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

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Tambah Diskusi',
               headerTitleAlign: 'center',
               // headerRight: () => <ButtonSaveHeader
               //    disable={desc == "" || loading}
               //    category="create"
               //    onPress={() => {
               //       handleCreate()
               //    }} />
               header: () => (
                  <AppHeader
                     title="Tambah Diskusi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={desc == "" || loading}
                           category="create"
                           onPress={() => {
                              handleCreate()
                           }} />
                     }
                  />
               )
            }}
         />
         {loading && <LoadingCenter />}
         <ScrollView showsVerticalScrollIndicator={false} style={[Styles.h100]}>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  onChange={setDesc}
                  multiline
                  bg={colors.card}
               />
               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               {
                  fileForm.length > 0
                  &&
                  <>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text style={[Styles.textDefaultSemiBold]}>File</Text>
                        <Text style={[Styles.textDefault]}>{fileForm.length} file</Text>
                     </View>
                     <View style={[Styles.borderAll, Styles.round05, Styles.p10, Styles.mb10, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>
                        {
                           fileForm.map((item, index) => (
                              <BorderBottomItem
                                 key={index}
                                 borderType={fileForm.length - 1 == index ? "none" : "bottom"}
                                 icon={<MaterialCommunityIcons name="file-outline" size={25} color={colors.text} />}
                                 title={item.name}
                                 titleWeight="normal"
                                 onPress={() => { setIndexDelFile(index); setModalFile(true) }}
                              />
                           ))
                        }
                     </View>
                  </>

               }
            </View>
         </ScrollView>

         <DrawerBottom animation="slide" isVisible={isModalFile} setVisible={setModalFile} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<Ionicons name="trash-outline" color={colors.text} size={25} />}
                  title="Hapus"
                  onPress={() => { deleteFile(indexDelFile) }}
               />
            </View>
         </DrawerBottom>
      </SafeAreaView>
   )
}