import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import PaperGridContent from "@/components/paperGridContent";
import ProgressBar from "@/components/progressBar";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetProject } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import {
   AntDesign,
   Ionicons,
   MaterialCommunityIcons,
} 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;
   title: string;
   desc: string;
   status: number;
   member: number;
   progress: number;
   createdAt: string;
};

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

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetProject({
            user: hasil,
            status: String(status),
            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();
   }, [status, search, group, cat]);

   return (
      <SafeAreaView>
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <ScrollView horizontal style={[Styles.mb10]}>
                  <ButtonTab
                     active={String(status)}
                     value="0"
                     onPress={() => {
                        router.push(
                           `/project?status=0&group=${group}&search=${search}&cat=${cat}`
                        );
                     }}
                     label="Segera"
                     icon={
                        <MaterialCommunityIcons
                           name="clock-alert-outline"
                           color={status == "0" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={String(status)}
                     value="1"
                     onPress={() => {
                        router.push(
                           `/project?status=1&group=${group}&search=${search}&cat=${cat}`
                        );
                     }}
                     label="Dikerjakan"
                     icon={
                        <MaterialCommunityIcons
                           name="progress-check"
                           color={status == "1" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={String(status)}
                     value="2"
                     onPress={() => {
                        router.push(
                           `/project?status=2&group=${group}&search=${search}&cat=${cat}`
                        );
                     }}
                     label="Selesai"
                     icon={
                        <Ionicons
                           name="checkmark-done-circle-outline"
                           color={status == "2" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={String(status)}
                     value="3"
                     onPress={() => {
                        router.push(
                           `/project?status=3&group=${group}&search=${search}&cat=${cat}`
                        );
                     }}
                     label="Batal"
                     icon={
                        <AntDesign
                           name="closecircleo"
                           color={status == "3" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
               </ScrollView>
               <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>
               <View style={[Styles.mv05]}>
                  <Text>Filter :
                     {
                        (entityUser.role == "supadmin" || entityUser.role == "developer") && nameGroup
                     }
                     {
                        (entityUser.role == 'user' || entityUser.role == 'coadmin')
                           ? (cat == 'null' || cat == 'undefined' || cat == undefined || cat == '' || cat == 'data-saya') ? 'Kegiatan Saya' : 'Semua Kegiatan'
                           : ''
                     }
                  </Text>
               </View>
               {
                  data.length > 0
                     ?
                     isList ? (
                        <View>
                           {data.map((item, index) => {
                              return (
                                 <BorderBottomItem
                                    key={index}
                                    onPress={() => { router.push(`/project/${item.id}`); }}
                                    borderType="bottom"
                                    icon={
                                       <View
                                          style={[Styles.iconContent, ColorsStatus.lightGreen]}
                                       >
                                          <AntDesign
                                             name="areachart"
                                             size={25}
                                             color={"#384288"}
                                          />
                                       </View>
                                    }
                                    title={item.title}
                                 />
                              );
                           })}
                        </View>
                     ) : (
                        <View>
                           {data.map((item, index) => {
                              return (
                                 <PaperGridContent
                                    key={index}
                                    onPress={() => {
                                       router.push(`/project/${item.id}`);
                                    }}
                                    content="page"
                                    title={item.title}
                                    headerColor="primary"
                                 >
                                    <ProgressBar value={item.progress} category="page" />
                                    <View style={[Styles.rowSpaceBetween]}>
                                       <Text style={[Styles.textDefault, Styles.cGray]}>
                                          {item.createdAt}
                                       </Text>
                                       <LabelStatus
                                          size="default"
                                          category={
                                             item.status === 0 ? 'primary' :
                                                item.status === 1 ? 'warning' :
                                                   item.status === 2 ? 'success' :
                                                      item.status === 3 ? 'error' :
                                                         'primary'
                                          }
                                          text={
                                             item.status === 0 ? 'SEGERA' :
                                                item.status === 1 ? 'DIKERJAKAN' :
                                                   item.status === 2 ? 'SELESAI' :
                                                      item.status === 3 ? 'DIBATALKAN' :
                                                         'SEGERA'
                                          }
                                       />
                                    </View>
                                 </PaperGridContent>
                              );
                           })}
                        </View>
                     )
                     :
                     <View style={[Styles.mt15]}>
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada kegiatan</Text>
                     </View>
               }
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
