import AppHeader from "@/components/AppHeader";
import SectionCancel from "@/components/sectionCancel";
import SectionProgress from "@/components/sectionProgress";
import HeaderRightTaskDetail from "@/components/task/headerTaskDetail";
import SectionFileTask from "@/components/task/sectionFileTask";
import SectionLinkTask from "@/components/task/sectionLinkTask";
import SectionMemberTask from "@/components/task/sectionMemberTask";
import SectionReportTask from "@/components/task/sectionReportTask";
import SectionTanggalTugasTask from "@/components/task/sectionTanggalTugasTask";
import Styles from "@/constants/Styles";
import { apiGetDivisionOneFeature, apiGetTaskOne } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { RefreshControl, SafeAreaView, ScrollView, View } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   id: string
   title: string
   desc: string
   reason: string
   status: number
   isActive: boolean
}

export default function DetailTaskDivision() {
   const { id, detail } = useLocalSearchParams<{ id: string, detail: string }>();
   const { token, decryptToken } = useAuthSession()
   const [data, setData] = useState<Props>()
   const [loading, setLoading] = useState(true)
   const [progress, setProgress] = useState(0)
   const update = useSelector((state: any) => state.taskUpdate)
   const [refreshing, setRefreshing] = useState(false)
   const [isMemberDivision, setIsMemberDivision] = useState(false);
   const [isAdminDivision, setIsAdminDivision] = useState(false);
   const entityUser = useSelector((state: any) => state.user);

   async function handleCheckMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivisionOneFeature({
            id,
            user: hasil,
            cat: "check-member",
         });

         setIsMemberDivision(response.data);

         const response2 = await apiGetDivisionOneFeature({
            id,
            user: hasil,
            cat: "check-admin",
         });
         setIsAdminDivision(response2.data);
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      handleCheckMember()
   }, [])


   async function handleLoad(cat: 'data' | 'progress') {
      try {
         if (cat == 'data') setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetTaskOne({ id: detail, user: hasil, cat: cat })
         if (cat == 'data') {
            setData(response.data)
         } else {
            setProgress(response.data.progress)
         }
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

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

   useEffect(() => {
      handleLoad('progress')
   }, [update.progress])

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

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: loading ? 'Loading...                            ' : data?.title,
               headerTitleAlign: 'center',
               // headerRight: () => (entityUser.role == "user" || entityUser.role == "coadmin") && !isMemberDivision
               //    ? <></>
               //    : <HeaderRightTaskDetail id={detail} division={id} status={data?.status} isAdminDivision={isAdminDivision} />,
               header: () => (
                  <AppHeader
                     title={loading ? 'Loading...' : data ? data?.title : ''}
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        (entityUser.role == "user" || entityUser.role == "coadmin") && !isMemberDivision
                           ? <></>
                           : <HeaderRightTaskDetail id={detail} division={id} status={data?.status} isAdminDivision={isAdminDivision} />
                     }
                  />
               )
            }}
         />
         <ScrollView
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
               />
            }
         >
            <View style={[Styles.p15, Styles.mb100]}>
               {
                  data?.reason != null && data?.reason != "" && <SectionCancel text={data?.reason} />
               }
               <SectionProgress text={`Kemajuan Kegiatan ${progress}%`} progress={progress} />
               <SectionReportTask refreshing={refreshing} />
               <SectionTanggalTugasTask refreshing={refreshing} isMemberDivision={isMemberDivision} />
               <SectionFileTask refreshing={refreshing} isMemberDivision={isMemberDivision} />
               <SectionLinkTask refreshing={refreshing} isMemberDivision={isMemberDivision} />
               <SectionMemberTask refreshing={refreshing} isAdminDivision={isAdminDivision} />
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}