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 { apiGetTask } 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;
   progress: number;
   member: number;
};

export default function ListTask() {
   const { id, status } = useLocalSearchParams<{ id: string; status: string }>();
   const [isList, setList] = useState(false);
   const { token, decryptToken } = useAuthSession();
   const [data, setData] = useState<Props[]>([]);
   const [search, setSearch] = useState("");
   const update = useSelector((state: any) => state.taskUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 3 })

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetTask({
            user: hasil,
            division: id,
            status,
            search,
         });
         setData(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

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

   useEffect(() => {
      handleLoad(true);
   }, [status, search]);

   return (
      <SafeAreaView>
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <ScrollView horizontal style={[Styles.mb10]}>
                  <ButtonTab
                     active={status}
                     value="0"
                     onPress={() => {
                        router.replace("./task?status=0");
                     }}
                     label="Segera"
                     icon={
                        <MaterialCommunityIcons
                           name="clock-alert-outline"
                           color={status == "0" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={status}
                     value="1"
                     onPress={() => {
                        router.replace("./task?status=1");
                     }}
                     label="Dikerjakan"
                     icon={
                        <MaterialCommunityIcons
                           name="progress-check"
                           color={status == "1" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={status}
                     value="2"
                     onPress={() => {
                        router.replace("./task?status=2");
                     }}
                     label="Selesai"
                     icon={
                        <Ionicons
                           name="checkmark-done-circle-outline"
                           color={status == "2" ? "white" : "black"}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={status}
                     value="3"
                     onPress={() => {
                        router.replace("./task?status=3");
                     }}
                     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>
               {

                  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) => (
                                 <BorderBottomItem
                                    key={index}
                                    onPress={() => {
                                       router.push(`./task/${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) => (
                                 <PaperGridContent
                                    key={index}
                                    onPress={() => {
                                       router.push(`./task/${item.id}`);
                                    }}
                                    content="page"
                                    title={item.title}
                                    headerColor="primary"
                                 >
                                    <ProgressBar category="page" value={item.progress} />
                                    <View style={[Styles.rowSpaceBetween]}>
                                       <Text></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>
                        )
                     ) : (
                        <Text
                           style={[
                              Styles.textDefault,
                              Styles.cGray,
                              { textAlign: "center" },
                           ]}
                        >
                           Tidak ada data
                        </Text>
                     )

               }
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
