import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
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 { 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 { 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 CreateTaskDivision() {
   const { colors } = useTheme();
   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 : 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={() => {
               //          handleBack();
               //       }}
               //    />
               // ),
               headerTitle: `Tambah Tugas`,
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={title == "" || entitiesMember.length == 0 || taskCreate.length == 0 || loading}
               //       category="create"
               //       onPress={() => { handleCreate() }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Tambah Tugas"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <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}
                  bg={colors.card}
                  errorText="Judul Tugas tidak boleh kosong"
               />

               {/* Tanggal & Tugas */}
               <View style={[
                  Styles.wrapPaper, Styles.mb15, Styles.sectionCard,
                  { backgroundColor: colors.card, borderColor: colors.icon + '18' }
               ]}>
                  <Pressable
                     onPress={() => router.push(`/division/${id}/task/create/task`)}
                     style={[Styles.sectionActionRow, { marginBottom: taskCreate.length > 0 ? 12 : 0 }]}
                  >
                     <View style={[Styles.sectionIconBox, { backgroundColor: colors.tabActive + '18' }]}>
                        <MaterialCommunityIcons name="calendar-check-outline" size={18} color={colors.tabActive} />
                     </View>
                     <View style={Styles.flex1}>
                        <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>Tanggal & Tugas</Text>
                        {taskCreate.length === 0 && (
                           <Text style={[Styles.textMediumNormal, { color: colors.dimmed }]}>Belum ada tugas ditambahkan</Text>
                        )}
                     </View>
                     {taskCreate.length > 0 && (
                        <View style={[Styles.sectionBadge, { backgroundColor: colors.tabActive + '18' }]}>
                           <Text style={[Styles.textSmallSemiBold, { color: colors.tabActive }]}>{taskCreate.length} tugas</Text>
                        </View>
                     )}
                     <MaterialCommunityIcons name="chevron-right" size={18} color={colors.dimmed} />
                  </Pressable>
                  {taskCreate.length > 0 && <SectionListAddTask showTitle={false} />}
               </View>

               {/* File */}
               <View style={[
                  Styles.wrapPaper, Styles.mb15, Styles.sectionCard,
                  { backgroundColor: colors.card, borderColor: colors.icon + '18' }
               ]}>
                  <Pressable
                     onPress={pickDocumentAsync}
                     style={[Styles.sectionActionRow, { marginBottom: fileForm.length > 0 ? 12 : 0 }]}
                  >
                     <View style={[Styles.sectionIconBox, { backgroundColor: colors.icon + '15' }]}>
                        <MaterialCommunityIcons name="paperclip" size={18} color={colors.dimmed} />
                     </View>
                     <View style={Styles.flex1}>
                        <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>File</Text>
                        {fileForm.length === 0 && (
                           <Text style={[Styles.textMediumNormal, { color: colors.dimmed }]}>Opsional — ketuk untuk upload</Text>
                        )}
                     </View>
                     {fileForm.length > 0 && (
                        <View style={[Styles.sectionBadge, { backgroundColor: colors.dimmed + '18' }]}>
                           <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed }]}>{fileForm.length} file</Text>
                        </View>
                     )}
                     <MaterialCommunityIcons name="chevron-right" size={18} color={colors.dimmed} />
                  </Pressable>
                  {fileForm.length > 0 && (
                     <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: 'transparent', 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>

               {/* Anggota */}
               <View style={[
                  Styles.wrapPaper, Styles.mb15, Styles.sectionCard,
                  { backgroundColor: colors.card, borderColor: colors.icon + '18' }
               ]}>
                  <Pressable
                     onPress={() => router.push(`/division/${id}/task/create/member`)}
                     style={[Styles.sectionActionRow, { marginBottom: entitiesMember.length > 0 ? 12 : 0 }]}
                  >
                     <View style={[Styles.sectionIconBox, { backgroundColor: colors.tabActive + '18' }]}>
                        <MaterialCommunityIcons name="account-group-outline" size={18} color={colors.tabActive} />
                     </View>
                     <View style={Styles.flex1}>
                        <Text style={[Styles.textDefaultSemiBold, { color: colors.text }]}>Anggota</Text>
                        {entitiesMember.length === 0 && (
                           <Text style={[Styles.textMediumNormal, { color: colors.dimmed }]}>Belum ada anggota dipilih</Text>
                        )}
                     </View>
                     {entitiesMember.length > 0 && (
                        <View style={[Styles.sectionBadge, { backgroundColor: colors.tabActive + '18' }]}>
                           <Text style={[Styles.textSmallSemiBold, { color: colors.tabActive }]}>{entitiesMember.length} orang</Text>
                        </View>
                     )}
                     <MaterialCommunityIcons name="chevron-right" size={18} color={colors.dimmed} />
                  </Pressable>
                  {entitiesMember.length > 0 && (
                     <View style={{ gap: 6 }}>
                        {entitiesMember.map((item: { img: any; name: any; position?: string }, index: any) => (
                           <View
                              key={index}
                              style={[Styles.listItemCard, { borderColor: colors.icon + '18' }]}
                           >
                              <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={[Styles.positionBadge, { backgroundColor: colors.dimmed + '15' }]}>
                                    <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={"member"}
            close={setSelect}
            onSelect={(value) => { }}
            title={"Pilih Anggota"}
            open={isSelect}
            idParent={''}
            valChoose={valChoose}
         />
      </SafeAreaView>
   );
}
