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 LoadingCenter from "@/components/loadingCenter";
import MenuItemRow from "@/components/menuItemRow";
import ModalSelect from "@/components/modalSelect";
import SelectForm from "@/components/selectForm";
import Text from '@/components/Text';
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiCreateDiscussionGeneral } from "@/lib/api";
import { setUpdateDiscussionGeneralDetail } from "@/lib/discussionGeneralDetail";
import { setMemberChoose } from "@/lib/memberChoose";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Ionicons, MaterialCommunityIcons, MaterialIcons } 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 CreateDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const entityUser = useSelector((state: any) => state.user);
   const userLogin = useSelector((state: any) => state.entities)
   const [chooseGroup, setChooseGroup] = useState({ val: "", label: "" });
   const [valChoose, setValChoose] = useState("")
   const [valSelect, setValSelect] = useState<"group" | "member">("group");
   const dispatch = useDispatch()
   const [disableBtn, setDisableBtn] = useState(true);
   const [isSelect, setSelect] = useState(false);
   const entitiesMember = useSelector((state: any) => state.memberChoose)
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const [loading, setLoading] = useState(false)
   const [fileForm, setFileForm] = useState<any[]>([])
   const [isModalFile, setModalFile] = useState(false)
   const [indexDelFile, setIndexDelFile] = useState<number>(0)
   const [dataForm, setDataForm] = useState({ idGroup: "", title: "", desc: "" });
   const [error, setError] = useState({ group: false, title: false, desc: false });

   function validationForm(cat: string, val: any, label?: string) {
      if (cat === "group") {
         setChooseGroup({ val, label: String(label) });
         dispatch(setMemberChoose([]))
         setDataForm({ ...dataForm, idGroup: val });
         setError({ ...error, group: val === "" || val === "null" });
      } else if (cat === "title") {
         setDataForm({ ...dataForm, title: val });
         setError({ ...error, title: val === "" || val === "null" });
      } else if (cat === "desc") {
         setDataForm({ ...dataForm, desc: val });
         setError({ ...error, desc: val === "" || val === "null" });
      }
   }

   function checkForm() {
      const hasError = Object.values(error).some(v => v)
      const hasEmpty = Object.values(dataForm).some(v => v === "")
      setDisableBtn(hasError || hasEmpty);
   }

   useEffect(() => { checkForm() }, [error, dataForm]);
   useEffect(() => { dispatch(setMemberChoose([])) }, [])

   function handleOpenMemberPicker() {
      if (entityUser.role === "supadmin" || entityUser.role === "developer") {
         if (chooseGroup.val !== "") {
            setSelect(true);
            setValSelect("member");
         } else {
            Toast.show({ type: 'small', text1: 'Pilih Lembaga Desa terlebih dahulu' })
         }
      } else {
         validationForm('group', userLogin.idGroup, userLogin.group);
         setValChoose(userLogin.idGroup)
         setSelect(true);
         setValSelect("member");
      }
   }

   const pickDocumentAsync = async () => {
      const result = await DocumentPicker.getDocumentAsync({ type: ["*/*"], multiple: true });
      if (!result.canceled) {
         let skipped = 0
         for (const asset of result.assets) {
            if (!asset.uri) continue
            if (fileForm.some(f => f.name === asset.name)) {
               skipped++
            } else {
               setFileForm(prev => [...prev, asset])
            }
         }
         if (skipped > 0) Toast.show({ type: 'small', text1: 'Beberapa file sudah ditambahkan' })
      }
   };

   function deleteFile(index: number) {
      setFileForm(fileForm.filter((_, 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({ ...dataForm, user: hasil, member: entitiesMember }))
         const response = await apiCreateDiscussionGeneral(fd)
         if (response.success) {
            dispatch(setMemberChoose([]))
            dispatch(setUpdateDiscussionGeneralDetail(!update))
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan data' })
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error: any) {
         console.error(error);
         Toast.show({ type: 'small', text1: error?.response?.data?.message || "Gagal menambahkan data" })
      } finally {
         setLoading(false)
      }
   }

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               header: () => (
                  <AppHeader
                     title="Tambah Diskusi"
                     showBack={true}
                     onPressLeft={() => { dispatch(setMemberChoose([])); router.back() }}
                     right={
                        <ButtonSaveHeader
                           category="create"
                           disable={disableBtn || entitiesMember.length === 0 || loading}
                           onPress={() => {
                              entitiesMember.length === 0
                                 ? Toast.show({ type: 'small', text1: 'Anda belum memilih anggota' })
                                 : handleCreate()
                           }}
                        />
                     }
                  />
               )
            }}
         />
         {loading && <LoadingCenter />}
         <ScrollView showsVerticalScrollIndicator={false} style={[Styles.h100, Styles.flex1, { backgroundColor: colors.background }]}>
            <View style={[Styles.p15, Styles.mb100]}>

               {(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="Judul"
                  type="default"
                  placeholder="Judul"
                  required
                  error={error.title}
                  bg={colors.card}
                  errorText="Judul tidak boleh kosong"
                  onChange={(val) => validationForm("title", val)}
               />

               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  error={error.desc}
                  bg={colors.card}
                  errorText="Diskusi tidak boleh kosong"
                  onChange={(val) => validationForm("desc", val)}
                  multiline
               />

               {/* 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); setModalFile(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={handleOpenMemberPicker}
                     style={[Styles.sectionActionRow, { marginBottom: entitiesMember.length > 0 ? 12 : 0 }]}
                  >
                     <View style={[Styles.sectionIconBox, { backgroundColor: colors.tabActive + '18' }]}>
                        <MaterialIcons name="people" 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} anggota</Text>
                        </View>
                     )}
                     <MaterialCommunityIcons name="chevron-right" size={18} color={colors.dimmed} />
                  </Pressable>
                  {entitiesMember.length > 0 && (
                     <View style={{ gap: 6 }}>
                        {entitiesMember.map((item: any, index: number) => (
                           <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>
                           </View>
                        ))}
                     </View>
                  )}
               </View>

            </View>
         </ScrollView>

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

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