import { ConstEnv } from "@/constants/ConstEnv"
import { valueGender } from "@/constants/Gender"
import { valueRoleUser } from "@/constants/RoleUser"
import Styles from "@/constants/Styles"
import { valueTypeEventRepeat } from "@/constants/TypeEventRepeat"
import { apiGetGroup, apiGetPosition, apiGetUser } from "@/lib/api"
import { setEntityFilterGroup } from "@/lib/filterSlice"
import { setMemberChoose } from "@/lib/memberChoose"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { AntDesign } from "@expo/vector-icons"
import { useEffect, useState } from "react"
import { Pressable, ScrollView, 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"
import Text from "./Text"

type Props = {
   open: boolean
   close: (value: boolean) => void
   title: string
   category: 'group' | 'status-task' | 'position' | 'role' | 'gender' | 'member' | 'type-event-repeat'
   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 { colors } = useTheme();
   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)
   }

   function handleLoadTypeEventRepeat() {
      setData(valueTypeEventRepeat)
   }


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

   function onChoose(val: string, label: string, img?: string, position?: 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, position }])
         }
      } 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' ? 90 : 75}>
         {
            category == 'member' &&
            <>
               <InputSearch onChange={setSearch} value={search} bg={"transparent"} />
               {
                  selectMember.length > 0
                     ?
                     <View>
                        <ScrollView horizontal style={[Styles.mb10, Styles.pv10]} showsHorizontalScrollIndicator={false}>
                           {
                              selectMember.map((item: any, index: any) => (
                                 <ImageWithLabel
                                    key={index}
                                    label={item.name}
                                    src={`${ConstEnv.url_storage}/files/${item.img}`}
                                    onClick={() => onChoose(item.idUser, item.name, item.img, item.position)}
                                 />
                              ))
                           }
                        </ScrollView>
                     </View>

                     :
                     <Text style={[Styles.textDefault, { color: colors.dimmed }, Styles.pv05, { textAlign: 'center' }]}>Tidak ada member yang dipilih</Text>
               }
            </>
         }
         <ScrollView showsVerticalScrollIndicator={false}>
            <View>
               {
                  category != 'status-task' ?
                     data.length > 0 ?
                        data.map((item: any, index: any) => (
                           <Pressable key={index} style={[Styles.itemSelectModal, {borderColor:colors.icon+'20'}]} onPress={() => { onChoose(item.id, item.name, item.img, item.position) }}>
                              {
                                 category == 'member'
                                    ?
                                    <View style={[Styles.rowItemsCenter]}>
                                       <ImageUser src={`${ConstEnv.url_storage}/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} color={colors.text} />
                                    :
                                    chooseValue.val == item.id && <AntDesign name="check" size={20} color={colors.text} />
                              }
                           </Pressable>
                        ))
                        :
                        <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
                     :
                     <>
                        {
                           dataStatus.map((item: any, index: any) => (
                              <Pressable key={index} style={[Styles.itemSelectModal, {borderColor:colors.icon+'20'}]} 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} color={colors.text} />
                                 }
                              </Pressable>
                           ))
                        }
                     </>
               }

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