import ButtonBackHeader from "@/components/buttonBackHeader";
import SectionCancel from "@/components/sectionCancel";
import SectionProgress from "@/components/sectionProgress";
import HeaderRightTaskDetail from "@/components/task/headerTaskDetail";
import SectionFileTask from "@/components/task/sectionFileTask";
import SectionMemberTask from "@/components/task/sectionMemberTask";
import SectionTanggalTugasTask from "@/components/task/sectionTanggalTugasTask";
import Styles from "@/constants/Styles";
import { apiGetTaskOne } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { 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)


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

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

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: loading ? 'Loading...' : data?.title,
               headerTitleAlign: 'center',
               headerRight: () => <HeaderRightTaskDetail id={detail} division={id} status={data?.status}/>,
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               {
                  data?.reason != null && data?.reason != "" && <SectionCancel text={data?.reason} />
               }
               <SectionProgress text={`Kemajuan Kegiatan ${progress}%`} progress={progress} />
               <SectionTanggalTugasTask />
               <SectionFileTask />
               <SectionMemberTask />
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}