import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ButtonSelect from "@/components/buttonSelect";
import DrawerBottom from "@/components/drawerBottom";
import ImageUser from "@/components/imageNew";
import { InputForm } from "@/components/inputForm";
import MenuItemRow from "@/components/menuItemRow";
import ModalSelect from "@/components/modalSelect";
import SectionListAddTask from "@/components/project/sectionListAddTask";
import Text from "@/components/Text";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiCreateTask } from "@/lib/api";
import { setMemberChoose } from "@/lib/memberChoose";
import { setTaskCreate } from "@/lib/taskCreate";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import * as DocumentPicker from "expo-document-picker";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, 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 CreateTaskDivision() {
   const { id } = useLocalSearchParams();
   const { token, decryptToken } = useAuthSession();
   const dispatch = useDispatch();
   const [isSelect, setSelect] = useState(false);
   const [valChoose, setValChoose] = useState("");
   const entitiesMember = useSelector((state: any) => state.memberChoose);
   const taskCreate = useSelector((state: any) => state.taskCreate);
   const update = useSelector((state: any) => state.taskUpdate)
   const [fileForm, setFileForm] = useState<any[]>([])
   const [indexDelFile, setIndexDelFile] = useState<number>(0)
   const [title, setTitle] = useState('')
   const [error, setError] = useState(false);
   const [isModal, setModal] = useState(false)
   const [loading, setLoading] = useState(false)
   let hitung = 0;

   useEffect(() => {
      if (hitung == 0) {
         dispatch(setTaskCreate([]));
         dispatch(setMemberChoose([]));
      }
      hitung++;
   }, []);


   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)])
      setModal(false)
   }


   function handleBack() {
      dispatch(setTaskCreate([]));
      dispatch(setMemberChoose([]));
      router.back();
   }

   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, task: taskCreate, member: entitiesMember, title, idDivision: id }
         ))

         const response = await apiCreateTask(fd)
         if (response.success) {
            dispatch(setUpdateTask({ ...update, data: !update.data }))
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
            handleBack()
         } 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={() => {
                        handleBack();
                     }}
                  />
               ),
               headerTitle: `Tambah Tugas`,
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={title == "" || entitiesMember.length == 0 || taskCreate.length == 0 || loading}
                     category="create"
                     onPress={() => { handleCreate() }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputForm
                  label="Judul Tugas"
                  type="default"
                  placeholder="Judul Tugas"
                  required
                  value={title}
                  onChange={(val) => {
                     setTitle(val);
                     val == "" || val == "null" ? setError(true) : setError(false);
                  }}
                  error={error}
                  errorText="Judul Tugas tidak boleh kosong"
               />
               <ButtonSelect value="Tambah Tanggal & Tugas" onPress={() => { router.push(`/division/${id}/task/create/task`); }} />
               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               <ButtonSelect value="Tambah Anggota" onPress={() => { router.push(`/division/${id}/task/create/member`); }} />
               <SectionListAddTask />
               {
                  fileForm.length > 0 && (
                     <View style={[Styles.mb15]}>
                        <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>File</Text>
                        <View style={[Styles.wrapPaper]}>
                           {
                              fileForm.map((item, index) => (
                                 <BorderBottomItem
                                    key={index}
                                    borderType="all"
                                    icon={<MaterialCommunityIcons name="file-outline" size={25} color="black" />}
                                    title={item.name}
                                    titleWeight="normal"
                                    onPress={() => { setIndexDelFile(index); setModal(true) }}
                                 />
                              ))
                           }
                        </View>
                     </View>
                  )
               }
               {entitiesMember.length > 0 && (
                  <View>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text>Anggota</Text>
                        <Text>Total {entitiesMember.length} Anggota</Text>
                     </View>

                     <View style={[Styles.borderAll, Styles.round10, Styles.p10]}>
                        {entitiesMember.map(
                           (item: { img: any; name: any }, index: any) => {
                              return (
                                 <BorderBottomItem
                                    key={index}
                                    borderType="bottom"
                                    icon={
                                       <ImageUser
                                          src={`${ConstEnv.url_storage}/files/${item.img}`}
                                          size="sm"
                                       />
                                    }
                                    title={item.name}
                                 />
                              );
                           }
                        )}
                     </View>
                  </View>
               )}

            </View>
         </ScrollView>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<Ionicons name="trash" color="black" size={25} />}
                  title="Hapus"
                  onPress={() => { deleteFile(indexDelFile) }}
               />
            </View>
         </DrawerBottom>

         <ModalSelect
            category={"member"}
            close={setSelect}
            onSelect={(value) => { }}
            title={"Pilih Anggota"}
            open={isSelect}
            idParent={''}
            valChoose={valChoose}
         />
      </SafeAreaView>
   );
}
