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 { useTheme } from "@/providers/ThemeProvider";
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";

// ... types ...
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('')
   const { colors } = useTheme();

   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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal melakukan pencarian"

         Toast.show({
            type: 'small',
            text1: message
         })
      }
   }


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


   return (
      <>
         <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
            <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}
                              tintColor={colors.icon}
                           />
                        }
                     >
                        {
                           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, { color: colors.icon }]}>Tidak ada data</Text>
                     </View>
               }

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