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 Skeleton from "@/components/skeleton";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
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 [statusFix, setStatusFix] = useState<'0' | '1' | '2' | '3'>('0')
   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);
   const update = useSelector((state: any) => state.projectUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 3 }, (_, index) => index)

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetProject({
            user: hasil,
            status: statusFix,
            search: search,
            group: String(group),
            kategori: String(cat),
         });

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

   useEffect(() => {
      handleLoad(false);
   }, [update.data]);


   useEffect(() => {
      handleLoad(true);
   }, [statusFix, search, group, cat]);

   return (
      <SafeAreaView>
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <ScrollView horizontal style={[Styles.mb10]}>
                  <ButtonTab
                     active={statusFix}
                     value="0"
                     onPress={() => { setStatusFix("0") }}
                     label="Segera"
                     icon={
                        <MaterialCommunityIcons
                           name="clock-alert-outline"
                           color={statusFix == "0" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={statusFix}
                     value="1"
                     onPress={() => { setStatusFix("1") }}
                     label="Dikerjakan"
                     icon={
                        <MaterialCommunityIcons
                           name="progress-check"
                           color={statusFix == "1" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={statusFix}
                     value="2"
                     onPress={() => { setStatusFix("2") }}
                     label="Selesai"
                     icon={
                        <Ionicons
                           name="checkmark-done-circle-outline"
                           color={statusFix == "2" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={statusFix}
                     value="3"
                     onPress={() => { setStatusFix("3") }}
                     label="Batal"
                     icon={
                        <AntDesign
                           name="closecircleo"
                           color={statusFix == "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>
               {
                  loading ?
                     isList ?
                        arrSkeleton.map((item, index) => (
                           <SkeletonTwoItem key={index} />
                        ))
                        :
                        arrSkeleton.map((item, index) => (
                           <Skeleton key={index} width={100} height={180} widthType="percent" borderRadius={10} />
                        ))
                     :
                     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>
   );
}
