import AppHeader from "@/components/AppHeader";
import BorderBottomItem from "@/components/borderBottomItem";
import ImageUser from "@/components/imageNew";
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 React, { useState } from "react";
import { RefreshControl, SafeAreaView, ScrollView, 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[]>([])
   const [refreshing, setRefreshing] = useState(false)
   const [search, setSearch] = useState('')

   async function handleSearch(cari: string) {
      try {
         setSearch(cari)
         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', })
      }
   }


   const handleRefresh = async () => {
      setRefreshing(true)
      handleSearch(search)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };


   return (
      <>
         <SafeAreaView>
            <Stack.Screen
               options={{
                  headerTitle: 'Pencarian',
                  headerTitleAlign: 'center',
                  header: () => (
                     <AppHeader title="Pencarian" showBack={true} onPressLeft={() => router.back()} />
                  )
               }}
            />
            <View style={[Styles.p15]}>
               <InputSearch onChange={handleSearch} />
               {
                  dataProject.length + dataDivisi.length + dataUser.length > 0
                     ?
                     <ScrollView
                        style={[Styles.h100]}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                           />
                        }
                     >
                        {
                           dataUser.length > 0 &&
                           <View style={[Styles.mv05, Styles.p10]}>
                              <Text>ANGGOTA</Text>
                              {
                                 dataUser.map((item, index) => (
                                    <BorderBottomItem
                                       key={index}
                                       borderType="bottom"
                                       icon={<ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} />}
                                       title={item.name}
                                       subtitle={`${item.group}-${item.position}`}
                                       onPress={() => {
                                          router.push(`/member/${item.id}`)
                                       }}
                                    />
                                 ))
                              }
                           </View>
                        }

                        {
                           dataDivisi.length > 0 &&
                           <View style={[Styles.mv05, Styles.p10]}>
                              <Text>DIVISI</Text>
                              {
                                 dataDivisi.map((item, index) => (
                                    <BorderBottomItem
                                       key={index}
                                       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.mv05, Styles.p10]}>
                              <Text>KEGIATAN</Text>
                              {
                                 dataProject.map((item, index) => (
                                    <BorderBottomItem
                                       key={index}
                                       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>
                        }
                     </ScrollView>
                     :
                     <View style={[Styles.contentItemCenter, Styles.mt10]}>
                        <Text style={[Styles.textInformation, Styles.cGray]}>Tidak ada data</Text>
                     </View>
               }

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