import AppHeader from "@/components/AppHeader";
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 LoadingCenter from "@/components/loadingCenter";
import MenuItemRow from "@/components/menuItemRow";
import ModalSelect from "@/components/modalSelect";
import SectionListAddTask from "@/components/project/sectionListAddTask";
import SelectForm from "@/components/selectForm";
import Text from "@/components/Text";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiCreateProject } from "@/lib/api";
import { setGroupChoose } from "@/lib/groupChoose";
import { setMemberChoose } from "@/lib/memberChoose";
import { setUpdateProject } from "@/lib/projectUpdate";
import { setTaskCreate } from "@/lib/taskCreate";
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 } from "expo-router";
import { useEffect, useState } from "react";
import {
   Pressable,
   SafeAreaView,
   ScrollView,
   View
} from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";

function getFileIcon(ext: string): keyof typeof MaterialCommunityIcons.glyphMap {
   if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic', 'heif'].includes(ext)) return 'image-outline'
   if (ext === 'pdf') return 'file-pdf-box'
   if (['mp4', 'mov', 'avi', 'mkv'].includes(ext)) return 'video-outline'
   if (['doc', 'docx'].includes(ext)) return 'file-word-outline'
   if (['xls', 'xlsx'].includes(ext)) return 'file-excel-outline'
   if (['zip', 'rar', '7z'].includes(ext)) return 'zip-box-outline'
   return 'file-outline'
}

function getFileColor(ext: string): string {
   if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic', 'heif'].includes(ext)) return '#339AF0'
   if (ext === 'pdf') return '#F03E3E'
   if (['mp4', 'mov', 'avi', 'mkv'].includes(ext)) return '#AE3EC9'
   if (['doc', 'docx'].includes(ext)) return '#1C7ED6'
   if (['xls', 'xlsx'].includes(ext)) return '#2F9E44'
   if (['zip', 'rar', '7z'].includes(ext)) return '#E8590C'
   return '#868E96'
}

export default function CreateProject() {
   const { colors } = useTheme();
   const [loading, setLoading] = useState(false)
   const { token, decryptToken } = useAuthSession();
   const [chooseGroup, setChooseGroup] = useState({ val: "", label: "" });
   const dispatch = useDispatch();
   const [valSelect, setValSelect] = useState<"group" | "member">("group");
   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.projectUpdate)
   const entityUser = useSelector((state: any) => state.user);
   const userLogin = useSelector((state: any) => state.entities)
   const [fileForm, setFileForm] = useState<any[]>([])
   const [indexDelFile, setIndexDelFile] = useState<number>(0)
   const [disableBtn, setDisableBtn] = useState(true)
   const [isModal, setModal] = useState(false)
   const [dataForm, setDataForm] = useState({
      idGroup: "",
      title: "",
   });
   const [error, setError] = useState({
      group: false,
      title: false,
      task: false,
      member: false,
   });
   const [hitung, setHitung] = useState(0)
   let hitungRefresh = 0;

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

   function validationForm(cat: string, val: any, label?: string) {
      if (cat == "group") {
         setChooseGroup({ val, label: String(label) });
         dispatch(setGroupChoose(val));
         dispatch(setMemberChoose([]));
         setDataForm({ ...dataForm, idGroup: val });
         if (val == "" || val == "null") {
            setError(error => ({ ...error, group: true }))
         } else {
            setError(error => ({ ...error, group: false }))
         }
      } else if (cat == "title") {
         setDataForm({ ...dataForm, title: val });
         if (val == "" || val == "null") {
            setError(error => ({ ...error, title: true }))
         } else {
            setError(error => ({ ...error, title: false }))
         }
      } else if (cat == "task" && hitung > 2) {
         if (taskCreate.length == 0) {
            setError(error => ({ ...error, task: true }))
         } else {
            setError(error => ({ ...error, task: false }))
         }
      } else if (cat == "member") {
         if (entitiesMember.length == 0) {
            setError(error => ({ ...error, member: true }))
         } else {
            setError(error => ({ ...error, member: false }))
         }
      }

      setHitung(hitung => hitung + 1)
   }

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

   useEffect(() => {
      validationForm('task', '');
   }, [taskCreate]);


   useEffect(() => {
      if (entityUser.role != "supadmin" && entityUser.role != "developer") {
         validationForm('group', userLogin.idGroup, userLogin.group);
      }
   }, []);

   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, ...dataForm }
         ))

         const response = await apiCreateProject(fd)
         if (response.success) {
            dispatch(setUpdateProject({ ...update, data: !update.data }))
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
            handleBack()
         } 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)
      }
   }


   function checkForm() {
      if (Object.values(error).some((v) => v == true) == true || Object.values(dataForm).some((v) => v == "") == true || entitiesMember.length == 0 || taskCreate.length == 0) {
         setDisableBtn(true)
      } else {
         setDisableBtn(false)
      }
   }

   useEffect(() => {
      checkForm()
   }, [error, dataForm, entitiesMember, taskCreate])

   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)
   }


   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          handleBack();
               //       }}
               //    />
               // ),
               headerTitle: "Tambah Kegiatan",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={disableBtn || loading}
               //       category="create"
               //       onPress={() => {
               //          handleCreate()
               //       }}
               //    />
               // ),
               header: () => (
                  <AppHeader title="Tambah Kegiatan"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={disableBtn || loading}
                           category="create"
                           onPress={() => {
                              handleCreate()
                           }}
                        />
                     }
                  />
               )
            }}
         />
         {
            loading && <LoadingCenter />
         }
         <ScrollView
            showsVerticalScrollIndicator={false}
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <View style={[Styles.p15]}>
               {
                  (entityUser.role == "supadmin" || entityUser.role == "developer")
                  &&
                  (
                     <SelectForm
                        label="Lembaga Desa"
                        placeholder="Pilih Lembaga Desa"
                        value={chooseGroup.label}
                        required
                        bg={colors.card}
                        onPress={() => {
                           setValChoose(chooseGroup.val);
                           setValSelect("group");
                           setSelect(true);
                        }}
                        error={error.group}
                        errorText="Lembaga Desa tidak boleh kosong"
                     />
                  )
               }
               <InputForm
                  label="Kegiatan"
                  type="default"
                  placeholder="Nama Kegiatan"
                  required
                  bg={colors.card}
                  value={dataForm.title}
                  error={error.title}
                  errorText="Nama kegiatan tidak boleh kosong"
                  onChange={(val) => {
                     validationForm("title", val);
                  }}
               />
               <ButtonSelect
                  value="Tambah Tanggal & Tugas"
                  onPress={() => {
                     router.push(`/project/create/task`);
                  }}
                  error={error.task}
                  errorText="Tanggal & Tugas tidak boleh kosong"
               />
               <ButtonSelect value="Upload File" onPress={pickDocumentAsync} />
               <ButtonSelect
                  value="Pilih Anggota"
                  onPress={() => {
                     if (entityUser.role == "supadmin" || entityUser.role == "developer") {
                        if (chooseGroup.val != "") {
                           router.push(`/project/create/member`);
                        } else {
                           Toast.show({ type: 'small', text1: "Pilih Lembaga Desa terlebih dahulu", })
                        }
                     } else {
                        router.push(`/project/create/member`);
                     }
                  }}
                  error={error.member}
                  errorText="Anggota tidak boleh kosong"
               />
               <SectionListAddTask />
               {fileForm.length > 0 && (
                  <View style={Styles.mb15}>
                     <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>File</Text>
                     <View style={Styles.fileGrid}>
                        {fileForm.map((item, index) => {
                           const ext = item.name.split('.').pop()?.toLowerCase() ?? ''
                           const baseName = item.name.includes('.') ? item.name.split('.').slice(0, -1).join('.') : item.name
                           const iconName = getFileIcon(ext)
                           const iconColor = getFileColor(ext)
                           return (
                              <Pressable
                                 key={index}
                                 onPress={() => { setIndexDelFile(index); setModal(true) }}
                                 style={[Styles.fileCard, { backgroundColor: colors.card, borderColor: colors.icon + '18' }]}
                              >
                                 <View style={[Styles.sectionIconBox, { backgroundColor: iconColor + '20' }]}>
                                    <MaterialCommunityIcons name={iconName} size={18} color={iconColor} />
                                 </View>
                                 <View style={Styles.flex1}>
                                    <Text style={Styles.textDefault} numberOfLines={1}>{baseName}</Text>
                                    <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed }]}>
                                       {ext.toUpperCase()}
                                    </Text>
                                 </View>
                              </Pressable>
                           )
                        })}
                     </View>
                  </View>
               )}
               {entitiesMember.length > 0 && (
                  <View style={Styles.mb15}>
                     <View style={[Styles.rowSpaceBetween, Styles.mv05]}>
                        <Text style={Styles.textDefaultSemiBold}>Anggota</Text>
                        <Text style={[Styles.textDefault, { color: colors.dimmed }]}>{entitiesMember.length} orang</Text>
                     </View>
                     <View style={{ gap: 6 }}>
                        {entitiesMember.map((item: { img: any; name: any; position?: string }, index: any) => (
                           <View
                              key={index}
                              style={{
                                 flexDirection: 'row',
                                 alignItems: 'center',
                                 backgroundColor: colors.card,
                                 borderRadius: 10,
                                 borderWidth: 1,
                                 borderColor: colors.icon + '18',
                                 paddingHorizontal: 12,
                                 paddingVertical: 10,
                                 gap: 12,
                              }}
                           >
                              <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                              <Text style={[Styles.textDefault, Styles.flex1, { color: colors.text }]} numberOfLines={1}>{item.name}</Text>
                              {item.position && (
                                 <View style={{
                                    backgroundColor: colors.dimmed + '15',
                                    borderRadius: 20,
                                    paddingHorizontal: 8,
                                    paddingVertical: 3,
                                 }}>
                                    <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed }]} numberOfLines={1}>
                                       {item.position}
                                    </Text>
                                 </View>
                              )}
                           </View>
                        ))}
                     </View>
                  </View>
               )}
            </View>
         </ScrollView>
         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<Ionicons name="trash-outline" color={colors.text} size={25} />}
                  title="Hapus"
                  onPress={() => { deleteFile(indexDelFile) }}
               />
            </View>
         </DrawerBottom>

         <ModalSelect
            category={valSelect}
            close={setSelect}
            onSelect={(value) => {
               validationForm(valSelect, value.val, value.label);
            }}
            title={valSelect == "group" ? "Lembaga Desa" : "Pilih Anggota"}
            open={isSelect}
            idParent={valSelect == "member" ? chooseGroup.val : ""}
            valChoose={valChoose}
         />
      </SafeAreaView>
   );
}
