import ButtonBackHeader from "@/components/buttonBackHeader"
import ButtonSaveHeader from "@/components/buttonSaveHeader"
import { InputForm } from "@/components/inputForm"
import Styles from "@/constants/Styles"
import { apiCreateDiscussion } from "@/lib/api"
import { setUpdateDiscussion } from "@/lib/discussionUpdate"
import { useAuthSession } from "@/providers/AuthProvider"
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 { 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)

   async function handleCreate() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         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) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setLoading(false)
      }
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Tambah Diskusi',
               headerTitleAlign: 'center',
               headerRight: () => <ButtonSaveHeader
                  disable={desc == "" || loading}
                  category="create"
                  onPress={() => {
                     handleCreate()
                  }} />
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  onChange={setDesc}
                  multiline
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}