import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import InputSearch from "@/components/inputSearch";
import Text from '@/components/Text';
import { ColorsStatus } from "@/constants/ColorsStatus";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetSearch } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { AntDesign, MaterialIcons } from "@expo/vector-icons";
import { router, Stack } from "expo-router";
import { useState } from "react";
import { FlatList, Image, SafeAreaView, View } from "react-native";
import Toast from "react-native-toast-message";

type PropsUser = {
   id: string
   name: string
   email: string
   position: string
   group: string
   img: string
}

type PropProject = {
   id: string
   title: string
   group: string
}

type PropDivisi = {
   id: string
   name: string
   desc: string
   group: string
}

export default function Search() {
   const { token, decryptToken } = useAuthSession()
   const [dataUser, setDataUser] = useState<PropsUser[]>([])
   const [dataDivisi, setDataDivisi] = useState<PropDivisi[]>([])
   const [dataProject, setDataProject] = useState<PropProject[]>([])

   async function handleSearch(cari: string) {
      try {
         if (cari.length > 3) {
            const user = await decryptToken(String(token?.current))
            const hasil = await apiGetSearch({ text: cari, user: user })
            if (hasil.success) {
               setDataUser(hasil.data.user)
               setDataDivisi(hasil.data.division)
               setDataProject(hasil.data.project)
            } else {
               return Toast.show({ type: 'small', text1: hasil.message, })
            }
         } else {
            setDataUser([])
            setDataDivisi([])
            setDataProject([])
         }
      } catch (error) {
         console.error(error)
         return Toast.show({ type: 'small', text1: 'Gagal melakukan pencarian', })
      }
   }


   return (
      <>
         <SafeAreaView>
            <Stack.Screen
               options={{
                  headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
                  headerTitle: 'Pencarian',
                  headerTitleAlign: 'center'
               }}
            />
            <View style={[Styles.p15]}>
               <InputSearch onChange={handleSearch} />
               {
                  dataProject.length + dataDivisi.length + dataUser.length > 0
                     ?
                     <View style={[Styles.wrapPaper, Styles.mb100]}>
                        {
                           dataUser.length > 0 &&
                           <View style={[Styles.mb05]}>
                              <Text>ANGGOTA</Text>
                              <FlatList
                                 data={dataUser}
                                 keyExtractor={(item) => String(item.id)}
                                 renderItem={({ item }) => (
                                    <BorderBottomItem
                                       borderType="bottom"
                                       icon={<Image
                                          source={{ uri: `${ConstEnv.url_storage}/files/${item.img}` }}
                                          style={[Styles.userProfileSmall]}
                                       />}
                                       title={item.name}
                                       subtitle={`${item.group}-${item.position}`}
                                       onPress={() => {
                                          router.push(`/member/${item.id}`)
                                       }}
                                    />
                                 )}
                              />
                           </View>
                        }

                        {
                           dataDivisi.length > 0 &&
                           <View style={[Styles.mb05]}>
                              <Text>DIVISI</Text>
                              <FlatList
                                 data={dataDivisi}
                                 keyExtractor={(item) => String(item.id)}
                                 renderItem={({ item }) => (
                                    <BorderBottomItem
                                       borderType="bottom"
                                       icon={
                                          <View style={[Styles.iconContent, ColorsStatus.primary]}>
                                             <MaterialIcons name="group" size={25} color="white" />
                                          </View>
                                       }
                                       title={item.name}
                                       subtitle={item.group}
                                       onPress={() => {
                                          router.push(`/division/${item.id}`)
                                       }}
                                    />
                                 )}
                              />
                           </View>
                        }


                        {
                           dataProject.length > 0 &&
                           <View style={[Styles.mb10]}>
                              <Text>KEGIATAN</Text>
                              <FlatList
                                 data={dataProject}
                                 keyExtractor={(item) => String(item.id)}
                                 renderItem={({ item }) => (
                                    <BorderBottomItem
                                       borderType="bottom"
                                       icon={
                                          <View style={[Styles.iconContent, ColorsStatus.primary]}>
                                             <AntDesign name="areachart" size={25} color="white" />
                                          </View>
                                       }
                                       title={item.title}
                                       subtitle={item.group}
                                       onPress={() => {
                                          router.push(`/project/${item.id}`)
                                       }}
                                    />
                                 )}
                              />
                           </View>
                        }


                     </View>
                     :
                     <View style={[Styles.contentItemCenter, Styles.mt10]}>
                        <Text style={[Styles.textInformation, Styles.cGray]}>Tidak ada data</Text>
                     </View>
               }

            </View>
         </SafeAreaView>
      </>
   )
}