import { valueGender } from "@/constants/Gender"
import { valueRoleUser } from "@/constants/RoleUser"
import Styles from "@/constants/Styles"
import { apiGetGroup, apiGetPosition, apiGetUser } from "@/lib/api"
import { setEntityFilterGroup } from "@/lib/filterSlice"
import { setMemberChoose } from "@/lib/memberChoose"
import { useAuthSession } from "@/providers/AuthProvider"
import { AntDesign } from "@expo/vector-icons"
import { useEffect, useState } from "react"
import { Pressable, ScrollView, Text, View } from "react-native"
import { useDispatch, useSelector } from "react-redux"
import { ButtonForm } from "./buttonForm"
import DrawerBottom from "./drawerBottom"
import ImageUser from "./imageNew"
import ImageWithLabel from "./imageWithLabel"
import InputSearch from "./inputSearch"

type Props = {
   open: boolean
   close: (value: boolean) => void
   title: string
   category: 'group' | 'status-task' | 'position' | 'role' | 'gender' | 'member'
   idParent?: string
   onSelect: (value: { val: string, label: string }) => void
   valChoose?: string
}

export default function ModalSelect({ open, close, title, category, idParent, onSelect, valChoose }: Props) {
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   const dispatch = useDispatch()
   const entitiesGroup = useSelector((state: any) => state.filterGroup)
   const [chooseValue, setChooseValue] = useState({ val: valChoose, label: '' })
   const [data, setData] = useState<any>([])
   const [search, setSearch] = useState('')
   const [selectMember, setSelectMember] = useState<any[]>([])
   const entitiesMember = useSelector((state: any) => state.memberChoose)
   const dataStatus = [
      {
         val: 0,
         label: 'Belum Selesai',
      },
      {
         val: 1,
         label: 'Selesai',
      }
   ]

   async function handleLoadGroup() {
      const hasil = await decryptToken(String(token?.current))
      const response = await apiGetGroup({ active: 'true', user: hasil, search: '' })
      dispatch(setEntityFilterGroup(response.data))
   }

   async function handleLoadPosition() {
      const hasil = await decryptToken(String(token?.current))
      if (idParent == undefined || idParent == '' || idParent == null) {
         setData([])
      } else {
         const response = await apiGetPosition({ active: 'true', user: hasil, search: '', group: idParent })
         setData(response.data)
      }
   }

   async function handleLoadMember() {
      const hasil = await decryptToken(String(token?.current))
      const response = await apiGetUser({ user: hasil, active: "true", search: search, group: String(idParent) })
      setData(response.data.filter((i: any) => i.idUserRole != 'supadmin'))
      if (entitiesMember.length > 0) {
         setSelectMember(entitiesMember)
      }
   }

   function handleLoadUserRole() {
      const filter = valueRoleUser.filter((v) => v.login == entityUser.role)[0]?.data
      setData(filter)
   }

   function handleLoadGender() {
      setData(valueGender)
   }


   useEffect(() => {
      if (category == 'group') {
         if (entitiesGroup.length == 0)
            handleLoadGroup()
         setData(entitiesGroup)
      } else if (category == 'position') {
         handleLoadPosition()
      } else if (category == "role") {
         handleLoadUserRole()
      } else if (category == "gender") {
         handleLoadGender()
      } else if (category == "member") {
         handleLoadMember()
      }
      setChooseValue({ ...chooseValue, val: valChoose })
   }, [dispatch, open, search]);

   function onChoose(val: string, label: string, img?: string) {
      if (category == "member") {
         if (selectMember.some((i: any) => i.idUser == val)) {
            setSelectMember(selectMember.filter((i: any) => i.idUser != val))
         } else {
            setSelectMember([...selectMember, { idUser: val, name: label, img }])
         }
      } else {
         setChooseValue({ val, label })
         onSelect({ val, label })
         close(false)
      }
   }

   function handleChooseMember() {
      dispatch(setMemberChoose(selectMember))
      close(false)
   }

   return (
      <DrawerBottom animation="none" isVisible={open} setVisible={close} title={title} height={(category == 'gender' || category == 'status-task') ? 25 : category == 'member' ? 100 : 75}>
         {
            category == 'member' &&
            <>
               <InputSearch onChange={setSearch} value={search} />
               {
                  selectMember.length > 0
                     ?
                     <View>
                        <ScrollView horizontal style={[Styles.mb10, Styles.pv10]}>
                           {
                              selectMember.map((item: any, index: any) => (
                                 <ImageWithLabel
                                    key={index}
                                    label={item.name}
                                    src={item.img}
                                    onClick={() => onChoose(item.idUser, item.name, item.img)}
                                 />
                              ))
                           }
                        </ScrollView>
                     </View>

                     :
                     <Text style={[Styles.textDefault, Styles.cGray, Styles.pv05, { textAlign: 'center' }]}>Tidak ada member yang dipilih</Text>
               }
            </>
         }
         <ScrollView>
            <View>
               {
                  category != 'status-task' ?
                     data.length > 0 ?
                        data.map((item: any, index: any) => (
                           <Pressable key={index} style={[Styles.itemSelectModal]} onPress={() => { onChoose(item.id, item.name, item.img) }}>
                              {
                                 category == 'member'
                                    ?
                                    <View style={[Styles.rowItemsCenter]}>
                                       <ImageUser src={`https://wibu-storage.wibudev.com/api/files/${item.img}`} border />
                                       <Text style={[Styles.textDefault, Styles.ml10]}>{item.name}</Text>
                                    </View>
                                    :
                                    <Text style={[chooseValue.val == item.id ? Styles.textDefaultSemiBold : Styles.textDefault]}>{item.name}</Text>
                              }
                              {
                                 (category == 'member')
                                    ?
                                    selectMember.some((i: any) => i.idUser == item.id) && <AntDesign name="check" size={20} />
                                    :
                                    chooseValue.val == item.id && <AntDesign name="check" size={20} />
                              }
                           </Pressable>
                        ))
                        :
                        <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
                     :
                     <>
                        {
                           dataStatus.map((item: any, index: any) => (
                              <Pressable key={index} style={[Styles.itemSelectModal]} onPress={() => {
                                 onSelect(item)
                                 close(false)
                              }}>
                                 <Text style={[chooseValue.val == item.val ? Styles.textDefaultSemiBold : Styles.textDefault]}>{item.label}</Text>
                                 {
                                    valChoose == item.val && <AntDesign name="check" size={20} />
                                 }
                              </Pressable>
                           ))
                        }
                     </>
               }

            </View>
         </ScrollView>
         {
            category == 'member' &&
            <ButtonForm
               onPress={() => { handleChooseMember() }}
               text="PILIH MEMBER"
               disabled={selectMember.length == 0}
            />
         }
      </DrawerBottom >
   )
}