import Styles from "@/constants/Styles"
import { apiGetGroup, apiGetTahunProject, apiGetTahunTask } from "@/lib/api"
import { setEntityFilterGroup } from "@/lib/filterSlice"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { router } from "expo-router"
import { useEffect, useState } from "react"
import { ScrollView, TouchableOpacity, View } from "react-native"
import { useDispatch, useSelector } from "react-redux"
import { ButtonForm } from "./buttonForm"
import DrawerBottom from "./drawerBottom"
import Text from './Text'


type Props = {
   open: boolean,
   close: (value: boolean) => void
   page: 'position' | 'member' | 'discussion' | 'project' | 'division' | 'division/task'
   category?: 'filter-group' | 'filter-data' | 'year-only',
   valueGroup?: string,
   valueYear?: string,
   dataPassing?: any
}

export default function ModalFilter({ open, close, page, category, valueGroup, valueYear, dataPassing }: Props) {
   const data = [
      {
         id: "data-saya",
         name: "Kegiatan Saya",
      },
      {
         id: "semua",
         name: "Semua Kegiatan",
      },
   ]
   const { token, decryptToken } = useAuthSession()
   const dispatch = useDispatch()
   const entities = useSelector((state: any) => state.filterGroup)
   const update = useSelector((state: any) => state.groupUpdate)
   const [chooseGroup, setChooseGroup] = useState(valueGroup || '')
   const [chooseYear, setChooseYear] = useState(valueYear || '')
   const [dataTahun, setDataTahun] = useState<{ id: string, name: string }[]>([])
   const [passingData, setPassingData] = useState(dataPassing)
   const { colors } = useTheme()

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

      if (page === 'project') {
         const responseTahun = await apiGetTahunProject({ user: hasil })
         setDataTahun(responseTahun.data)
      } else if (page === 'division/task') {
         const responseTahun = await apiGetTahunTask({ user: hasil, division: passingData })
         setDataTahun(responseTahun.data)
      }

   }

   useEffect(() => {
      handleLoad()
   }, [dispatch, update]);




   return (
      <DrawerBottom animation="slide" isVisible={open} setVisible={close} title="Pilih Preferensi" height={75}>
         <View style={{ justifyContent: 'space-between', flex: 1 }}>
            <ScrollView>
               {
                  category != "year-only" &&
                  <View>
                     <Text style={[Styles.textDefaultSemiBold, Styles.mb05]}>{category == "filter-data" ? "Filter Data" : "Lembaga Desa"}</Text>
                     <View style={[Styles.rowOnly, { flexWrap: 'wrap' }]}>
                        {
                           category == "filter-data"
                              ?
                              data.map((item: any, index: any) => (
                                 <TouchableOpacity
                                    key={index}
                                    style={[
                                       Styles.chip,
                                       { borderColor: colors.dimmed },
                                       chooseGroup == item.id && { backgroundColor: colors.primary },
                                    ]}
                                    onPress={() => { setChooseGroup(item.id) }}
                                 >
                                    {/* {chooseGroup == item.id && (
                                 <View style={Styles.checkIcon}>
                                    <Ionicons name="checkmark" size={14} color="white" />
                                 </View>
                              )} */}

                                    <Text
                                       style={[
                                          Styles.chipText,
                                          { color: colors.text },
                                          chooseGroup == item.id && Styles.chipTextSelected,
                                       ]}
                                    >
                                       {item.name}
                                    </Text>
                                 </TouchableOpacity>
                                 // <Pressable key={index} style={[Styles.itemSelectModal]} onPress={() => { setChooseGroup(item.id) }}>
                                 //    <Text style={[chooseGroup == item.id ? Styles.textDefaultSemiBold : Styles.textDefault]}>{item.name}</Text>
                                 //    {
                                 //       chooseGroup == item.id && <AntDesign name="check" size={20} color={'black'} />
                                 //    }
                                 // </Pressable>
                              ))
                              :
                              entities.map((item: any, index: any) => (
                                 <TouchableOpacity
                                    key={index}
                                    style={[
                                       Styles.chip,
                                       { borderColor: colors.dimmed },
                                       chooseGroup == item.id && { backgroundColor: colors.primary },
                                    ]}
                                    activeOpacity={0.8}
                                    onPress={() => { setChooseGroup(item.id) }}
                                 >
                                    {/* {chooseGroup == item.id && (
                                 <View style={Styles.checkIcon}>
                                    <Ionicons name="checkmark" size={14} color="white" />
                                 </View>
                              )} */}

                                    <Text
                                       style={[
                                          Styles.chipText,
                                          { color: colors.text },
                                          chooseGroup == item.id && Styles.chipTextSelected,
                                       ]}
                                    >
                                       {item.name}
                                    </Text>
                                 </TouchableOpacity>
                                 // <Pressable key={index} style={[Styles.itemSelectModal]} onPress={() => { setChooseGroup(item.id) }}>
                                 //    <Text style={[chooseGroup == item.id ? Styles.textDefaultSemiBold : Styles.textDefault]}>{item.name}</Text>
                                 //    {
                                 //       chooseGroup == item.id && <AntDesign name="check" size={20} color={'black'}/>
                                 //    }
                                 // </Pressable>
                              ))
                        }
                     </View>
                  </View>
               }

               {(page == "project" || page == "division/task") && (
                  <View>
                     <Text style={[Styles.textDefaultSemiBold, Styles.mb05]}>Tahun</Text>
                     <View style={[Styles.rowOnly, { flexWrap: 'wrap' }]}>
                        {
                           dataTahun.map((item: { id: string, name: string }, index: number) => (
                              <TouchableOpacity
                                 key={index}
                                 style={[
                                    Styles.chip,
                                    { borderColor: colors.dimmed },
                                    chooseYear == item.id && { backgroundColor: colors.primary },
                                 ]}
                                 activeOpacity={0.8}
                                 onPress={() => { setChooseYear(item.id) }}
                              >
                                 <Text
                                    style={[
                                       Styles.chipText,
                                       { color: colors.text },
                                       chooseYear == item.id && Styles.chipTextSelected,
                                    ]}
                                 >
                                    {item.name}
                                 </Text>
                              </TouchableOpacity>
                           ))
                        }
                     </View>
                  </View>
               )}
            </ScrollView>
            <View>
               <ButtonForm text="Terapkan" onPress={() => {
                  close(false)
                  page == 'project' ?
                     category == "year-only"
                        ?
                        router.replace(`/${page}?status=0&year=${chooseYear}`)
                        :
                        category == "filter-data"
                           ?
                           router.replace(`/${page}?status=0&cat=${chooseGroup}&year=${chooseYear}`)
                           :
                           router.replace(`/${page}?status=0&group=${chooseGroup}&year=${chooseYear}`)
                     :
                     page == "division/task" ?
                        router.replace(`/division/${dataPassing}/task?status=0&year=${chooseYear}`)
                        :
                        router.replace(`/${page}?active=true&group=${chooseGroup}`)
               }} />
            </View>
         </View>
      </DrawerBottom>
   )
}