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 Text from "@/components/Text";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetTask } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import {
   AntDesign,
   Ionicons,
   MaterialCommunityIcons,
} from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, RefreshControl, ScrollView, View, VirtualizedList } from "react-native";
import { useSelector } from "react-redux";
import AsyncStorage from "@react-native-async-storage/async-storage";

type Props = {
   id: string;
   title: string;
   desc: string;
   status: number;
   progress: number;
   member: number;
};

export default function ListTask() {
   const { colors } = useTheme()
   const { id, status, year } = useLocalSearchParams<{ id: string; status: string; year: string }>()
   const [isList, setList] = useState(false)
   const { token, decryptToken } = useAuthSession()

   useEffect(() => {
      AsyncStorage.getItem('division_view_mode').then((val) => {
         if (val !== null) setList(val === 'list')
      })
   }, [])

   function toggleView() {
      const next = !isList
      setList(next)
      AsyncStorage.setItem('division_view_mode', next ? 'list' : 'grid')
   }
   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 })
   const [statusFix, setStatusFix] = useState<'0' | '1' | '2' | '3'>('0')
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = useState(false)
   const [refreshing, setRefreshing] = useState(false)
   const [isYear, setYear] = useState("")


   async function handleLoad(loading: boolean, thisPage: number) {
      try {
         setWaiting(true)
         setLoading(loading)
         setPage(thisPage)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetTask({
            user: hasil,
            division: id,
            status: statusFix,
            search,
            page: thisPage,
            year
         });

         setYear(response.tahun)

         if (thisPage == 1) {
            setData(response.data);
         } else if (thisPage > 1 && response.data.length > 0) {
            setData([...data, ...response.data]);
         } else {
            return;
         }
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
         setWaiting(false)
      }
   }

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

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

   const loadMoreData = () => {
      if (waiting) return
      setTimeout(() => {
         handleLoad(false, page + 1)
      }, 1000);
   }

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

   const getItem = (_data: unknown, index: number): Props => ({
      id: data[index].id,
      title: data[index].title,
      desc: data[index].desc,
      status: data[index].status,
      progress: data[index].progress,
      member: data[index].member,
   })

   return (
      <View style={[Styles.p15, Styles.flex1, { backgroundColor: colors.background }]}>
         <View>
            <ScrollView horizontal style={[Styles.mb10]} showsHorizontalScrollIndicator={false}>
               <ButtonTab
                  active={statusFix}
                  value="0"
                  onPress={() => { setStatusFix("0") }}
                  label="Segera"
                  icon={
                     <MaterialCommunityIcons
                        name="clock-alert-outline"
                        color={statusFix == "0" ? "white" : colors.dimmed}
                        size={20}
                     />
                  }
                  n={4}
               />
               <ButtonTab
                  active={statusFix}
                  value="1"
                  onPress={() => { setStatusFix("1") }}
                  label="Dikerjakan"
                  icon={
                     <MaterialCommunityIcons
                        name="progress-check"
                        color={statusFix == "1" ? "white" : colors.dimmed}
                        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" : colors.dimmed}
                        size={20}
                     />
                  }
                  n={4}
               />
               <ButtonTab
                  active={statusFix}
                  value="3"
                  onPress={() => { setStatusFix("3") }}
                  label="Batal"
                  icon={
                     <AntDesign
                        name="closecircleo"
                        color={statusFix == "3" ? "white" : colors.dimmed}
                        size={20}
                     />
                  }
                  n={4}
               />
            </ScrollView>
            <View style={[Styles.rowSpaceBetween, { alignItems: 'center' }]}>
               <InputSearch width={68} onChange={setSearch} />
               <Pressable onPress={toggleView}>
                  <MaterialCommunityIcons
                     name={isList ? "format-list-bulleted" : "view-grid"}
                     color={colors.text}
                     size={30}
                  />
               </Pressable>
            </View>
         </View>
         <View style={[Styles.mv05]}>
            <View style={[Styles.rowOnly]}>
               <Text style={[Styles.mr05]}>Filter :</Text>
               <LabelStatus size="small" category="secondary" text={isYear} style={[Styles.mr05]} />
            </View>
         </View>
         <View style={[{ flex: 2 }]}>
            {
               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 style={[Styles.h100]}>
                           <VirtualizedList
                              data={data}
                              getItemCount={() => data.length}
                              getItem={getItem}
                              renderItem={({ item, index }) => (
                                 <BorderBottomItem
                                    key={index}
                                    onPress={() => {
                                       router.push(`./task/${item.id}`);
                                    }}
                                    borderType="bottom"
                                    bgColor="transparent"
                                    icon={
                                       <View style={[Styles.iconContent]}>
                                          <AntDesign name="areachart" size={25} color={"black"} />
                                       </View>
                                    }
                                    title={item.title}
                                 />
                              )}
                              keyExtractor={(item, index) => index.toString()}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                    tintColor={colors.icon}
                                 />
                              }
                           />
                           {/* {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 style={[Styles.h100]}>
                           <VirtualizedList
                              data={data}
                              getItemCount={() => data.length}
                              getItem={getItem}
                              renderItem={({ item, index }) => (
                                 <PaperGridContent
                                    key={index}
                                    onPress={() => {
                                       router.push(`./task/${item.id}`);
                                    }}
                                    content="page"
                                    title={item.title}
                                    headerColor="primary"
                                 >
                                    <ProgressBar category="list" value={item.progress} />
                                    <View style={[Styles.rowSpaceBetween]}>
                                       <Text> </Text>
                                       <LabelStatus
                                          size="default"
                                          category={
                                             item.status === 0 ? 'secondary' :
                                                item.status === 1 ? 'warning' :
                                                   item.status === 2 ? 'success' :
                                                      item.status === 3 ? 'error' :
                                                         'secondary'
                                          }
                                          text={
                                             item.status === 0 ? 'SEGERA' :
                                                item.status === 1 ? 'DIKERJAKAN' :
                                                   item.status === 2 ? 'SELESAI' :
                                                      item.status === 3 ? 'DIBATALKAN' :
                                                         'SEGERA'
                                          }
                                       />
                                    </View>
                                 </PaperGridContent>
                              )}
                              keyExtractor={(item, index) => index.toString()}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                    tintColor={colors.icon}
                                 />
                              }
                           />
                           {/* {data.map((item, index) => (
                              <PaperGridContent
                                 key={index}
                                 onPress={() => {
                                    router.push(`./task/${item.id}`);
                                 }}
                                 content="page"
                                 title={item.title}
                                 headerColor="primary"
                              >
                                 <ProgressBar category="list" 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.textCenter]} >
                        Tidak ada data
                     </Text>
                  )

            }
         </View >
      </View >
   );
}
