import AppHeader from "@/components/AppHeader";
import GuideOverlay from "@/components/GuideOverlay";
import HeaderRightProjectDetail from "@/components/project/headerProjectDetail";
import SectionFile from "@/components/project/sectionFile";
import SectionLink from "@/components/project/sectionLink";
import SectionMember from "@/components/project/sectionMember";
import SectionReportProject from "@/components/project/sectionReportProject";
import SectionTanggalTugasProject from "@/components/project/sectionTanggalTugas";
import SectionCancel from "@/components/sectionCancel";
import SectionProgress from "@/components/sectionProgress";
import Styles from "@/constants/Styles";
import { apiGetProjectOne } 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 React, { useEffect, useState } from "react";
import { RefreshControl, SafeAreaView, ScrollView, View } from "react-native";
import { useSelector } from "react-redux";


type Props = {
   id: string,
   idVillage: string,
   idGroup: string,
   title: string,
   status: number,
   desc: string,
   reason: string,
   isActive: string,
   createdBy: string,
   createdAt: string,
   updatedAt: string,
}

export default function DetailProject() {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [data, setData] = useState<Props>()
   const [progress, setProgress] = useState(0)
   const [taskStats, setTaskStats] = useState<{ done: number, total: number } | undefined>()
   const [loading, setLoading] = useState(true)
   const update = useSelector((state: any) => state.projectUpdate)
   const [isMember, setIsMember] = useState(false)
   const entityUser = useSelector((state: any) => state.user)
   const [refreshing, setRefreshing] = useState(false)
   const { visible: guideVisible, dismiss: dismissGuide } = useGuide('project-detail')

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

   async function handleLoadTaskStats() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetProjectOne({ user: hasil, cat: 'task', id: id })
         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 checkMember() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetProjectOne({ user: hasil, cat: 'member', id: id })
         const cekMember = response.data.some((i: any) => i.idUser == hasil)
         setIsMember(cekMember)
      } catch (error) {
         console.error(error)
      }
   }

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

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

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

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


   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={[Styles.flex1, { 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") && !isMember ? null : <HeaderRightProjectDetail id={id} status={data?.status} />,
               header: () => (
                  <AppHeader
                     title={loading ? 'Loading...' : data && data?.title || ''}
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        (entityUser.role == "user" || entityUser.role == "coadmin") && !isMember ? null : <HeaderRightProjectDetail id={id} status={data?.status} />
                     }
                  />
               )
            }}
         />
         <GuideOverlay visible={guideVisible} steps={GUIDE_PROJECT_DETAIL} onDismiss={dismissGuide} />
         <ScrollView
            style={[Styles.h100, { backgroundColor: colors.background }]}
            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} />
               <SectionReportProject refreshing={refreshing} />
               <SectionTanggalTugasProject status={data?.status} member={isMember} refreshing={refreshing} idGroup={data?.idGroup ?? ''} />
               <SectionFile status={data?.status} member={isMember} refreshing={refreshing} />
               <SectionLink status={data?.status} member={isMember} refreshing={refreshing} />
               <SectionMember status={data?.status} refreshing={refreshing} />
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}