import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import InputSearch from "@/components/inputSearch";
import PaperGridContent from "@/components/paperGridContent";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetDivision } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import {
   AntDesign,
   Feather,
   Ionicons,
   MaterialCommunityIcons,
   MaterialIcons,
} from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, SafeAreaView, ScrollView, Text, View } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   id: string;
   name: string;
   desc: string;
   jumlah_member: number;
};

export default function ListDivision() {
   const { active, group, cat } = useLocalSearchParams<{
      active?: string;
      group?: string;
      cat?: string;
   }>();
   const [isList, setList] = useState(false);
   const entityUser = useSelector((state: any) => state.user);
   const { token, decryptToken } = useAuthSession();
   const [search, setSearch] = useState("");
   const [nameGroup, setNameGroup] = useState("");
   const [data, setData] = useState<Props[]>([]);
   const update = useSelector((state: any) => state.divisionUpdate)

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivision({
            user: hasil,
            active: String(active),
            search: search,
            group: String(group),
            kategori: String(cat),
         });

         if (response.success) {
            setData(response.data);
            setNameGroup(response.filter.name);
         }
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      handleLoad();
   }, [active, search, group, cat, update]);

   return (
      <SafeAreaView>
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               {
                  entityUser.role != "user" && entityUser.role != "coadmin" ?
                     <View style={[Styles.wrapBtnTab]}>
                        <ButtonTab
                           active={active == "false" ? "false" : "true"}
                           value="true"
                           onPress={() => {
                              router.replace(`/division?active=true&search=${search}&group=${group}&cat=${cat}`);
                           }}
                           label="Aktif"
                           icon={
                              <Feather
                                 name="check-circle"
                                 color={active == "false" ? "black" : "white"}
                                 size={20}
                              />
                           }
                           n={2}
                        />
                        <ButtonTab
                           active={active == "false" ? "false" : "true"}
                           value="false"
                           onPress={() => {
                              router.replace(`/division?active=false&search=${search}&group=${group}&cat=${cat}`);
                           }}
                           label="Tidak Aktif"
                           icon={
                              <AntDesign
                                 name="closecircleo"
                                 color={active == "true" ? "black" : "white"}
                                 size={20}
                              />
                           }
                           n={2}
                        />
                     </View>
                     :
                     <View style={[Styles.wrapBtnTab]}>
                        <ButtonTab
                           active={cat == "semua" ? "false" : "true"}
                           value="true"
                           onPress={() => {
                              router.replace(`/division?&search=${search}&group=${group}&cat=divisi-saya`);
                           }}
                           label="Divisi Saya"
                           icon={
                              <Ionicons
                                 name="file-tray-outline"
                                 color={cat == "semua" ? "black" : "white"}
                                 size={20}
                              />
                           }
                           n={2}
                        />
                        <ButtonTab
                           active={cat == "semua" ? "false" : "true"}
                           value="false"
                           onPress={() => {
                              router.replace(`/division?&search=${search}&group=${group}&cat=semua`);
                           }}
                           label="Semua Divisi"
                           icon={
                              <Ionicons
                                 name="file-tray-stacked-outline"
                                 color={cat == "semua" ? "white" : "black"}
                                 size={20}
                              />
                           }
                           n={2}
                        />
                     </View>
               }

               <View style={[Styles.rowSpaceBetween]}>
                  <InputSearch width={68} onChange={setSearch} />
                  <Pressable
                     onPress={() => {
                        setList(!isList);
                     }}
                  >
                     <MaterialCommunityIcons
                        name={isList ? "format-list-bulleted" : "view-grid"}
                        color={"black"}
                        size={30}
                     />
                  </Pressable>
               </View>
               {(entityUser.role == "supadmin" ||
                  entityUser.role == "developer") && (
                     <View style={[Styles.mv05]}>
                        <Text>Filter : {nameGroup}</Text>
                     </View>
                  )}

               {
                  data.length == 0 ? (
                     <View style={[Styles.mt15]}>
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
                     </View>
                  ) : (
                     isList ? (
                        <View>
                           {data.map((item, index) => (
                              <BorderBottomItem
                                 key={index}
                                 onPress={() => { }}
                                 borderType="bottom"
                                 icon={
                                    <View style={[Styles.iconContent, ColorsStatus.lightGreen]}>
                                       <MaterialIcons name="group" size={25} color={"#384288"} />
                                    </View>
                                 }
                                 title={item.name}
                                 titleWeight="normal"
                              />
                           ))}
                        </View>
                     ) : (
                        <View>
                           {data.map((item, index) => (
                              <PaperGridContent
                                 key={index}
                                 onPress={() => {
                                    router.push(`/division/${item.id}`);
                                 }}
                                 content="page"
                                 title={item.name}
                                 headerColor="primary"
                                 contentPosition="top"
                              >
                                 <Text style={[Styles.textDefault]} numberOfLines={2} ellipsizeMode="tail">{item.desc}</Text>
                              </PaperGridContent>
                           ))}
                        </View>
                     )
                  )
               }
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
