import AppHeader from "@/components/AppHeader";
import GuideOverlay from "@/components/GuideOverlay";
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 { GUIDE_PROJECT_DETAIL } from "@/lib/guideSteps";
import { useGuide } from "@/lib/useGuide";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
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
   idGroup: string
}

export default function DetailTaskDivision() {
   const { colors } = useTheme();
   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 [taskStats, setTaskStats] = useState<{ done: number, total: number } | undefined>()
   const update = useSelector((state: any) => state.taskUpdate)
   const [refreshing, setRefreshing] = useState(false)
   const [isMemberDivision, setIsMemberDivision] = useState(false);
   const { visible: guideVisible, dismiss: dismissGuide } = useGuide('division-task-detail')
   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 handleLoadTaskStats() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetTaskOne({ id: detail, user: hasil, cat: 'task' })
         const tasks: { status: number }[] = response.data
         setTaskStats({ done: tasks.filter(t => t.status === 1).length, total: tasks.length })
      } catch (error) {
         console.error(error)
      }
   }

   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])

   useEffect(() => {
      handleLoadTaskStats()
   }, [update.task])

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

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <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} />
                     }
                  />
               )
            }}
         />
         <GuideOverlay visible={guideVisible} steps={GUIDE_PROJECT_DETAIL} onDismiss={dismissGuide} />
         <ScrollView
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
                  tintColor={colors.icon}
               />
            }
         >
            <View style={[Styles.p15, Styles.mb100]}>
               {
                  data?.reason != null && data?.reason != "" && <SectionCancel text={data?.reason} />
               }
               <SectionProgress progress={progress} doneCount={taskStats?.done} totalCount={taskStats?.total} />
               <SectionReportTask refreshing={refreshing} />
               <SectionTanggalTugasTask refreshing={refreshing} isMemberDivision={isMemberDivision} isAdminDivision={isAdminDivision} status={data?.status} idGroup={data?.idGroup ?? ''} />
               <SectionFileTask refreshing={refreshing} isMemberDivision={isMemberDivision} />
               <SectionLinkTask refreshing={refreshing} isMemberDivision={isMemberDivision} />
               <SectionMemberTask refreshing={refreshing} isAdminDivision={isAdminDivision} />
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}