import Styles from "@/constants/Styles";
import { apiDeleteTaskTugas, apiGetTaskOne, apiUpdateStatusTaskDivision } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";
import AlertKonfirmasi from "../alertKonfirmasi";
import DrawerBottom from "../drawerBottom";
import ItemSectionTanggalTugas from "../itemSectionTanggalTugas";
import MenuItemRow from "../menuItemRow";
import ModalSelect from "../modalSelect";
import SkeletonTask from "../skeletonTask";
import Text from "../Text";
import ModalListDetailTugasTask from "./modalListDetailTugasTask";


type Props = {
   id: string;
   title: string;
   status: number;
   dateStart: string;
   dateEnd: string;
}

export default function SectionTanggalTugasTask({ refreshing, isMemberDivision }: { refreshing: boolean, isMemberDivision: boolean }) {
   const { colors } = useTheme()
   const dispatch = useDispatch()
   const entityUser = useSelector((state: any) => state.user);
   const update = useSelector((state: any) => state.taskUpdate)
   const [isModal, setModal] = useState(false)
   const [isSelect, setSelect] = useState(false)
   const { token, decryptToken } = useAuthSession()
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 })
   const [modalDetail, setModalDetail] = useState(false)
   const { id, detail } = useLocalSearchParams<{ id: string, detail: string }>();
   const [data, setData] = useState<Props[]>([])
   const [tugas, setTugas] = useState({
      id: '',
      status: 0,
   })

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

   async function handleUpdate(status: number) {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiUpdateStatusTaskDivision({
            user: hasil,
            idProject: detail,
            status: status,
         }, tugas.id);
         if (response.success) {
            dispatch(setUpdateTask({ ...update, progress: !update.progress, task: !update.task }))
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error);
         Toast.show({ type: 'small', text1: 'Gagal mengubah data', })
      } finally {
         setSelect(false)
      }
   }

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

   useEffect(() => {
      if (refreshing)
         handleLoad(false);
   }, [refreshing]);


   useEffect(() => {
      handleLoad(true)
   }, [])


   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiDeleteTaskTugas({
            user: hasil,
            idProject: detail,
         }, tugas.id);
         if (response.success) {
            dispatch(setUpdateTask({ ...update, progress: !update.progress, task: !update.task }))
            Toast.show({ type: 'small', text1: 'Berhasil menghapus data', })
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error);
         Toast.show({ type: 'small', text1: 'Gagal menghapus data', })
      } finally {
         setModal(false);
      }
   }


   return (
      <>
         <View style={[Styles.mb15, Styles.mt10]}>
            <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>Tanggal & Tugas</Text>
            <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.background }]}>
               {
                  loading ?
                     arrSkeleton.map((item, index) => {
                        return (
                           <SkeletonTask key={index} />
                        )
                     })
                     :
                     data.length > 0
                        ?
                        data.map((item, index) => {
                           return (
                              <ItemSectionTanggalTugas
                                 key={index}
                                 done={item.status === 1}
                                 title={item.title}
                                 dateStart={item.dateStart}
                                 dateEnd={item.dateEnd}
                                 onPress={() => {
                                    setTugas({
                                       id: item.id,
                                       status: item.status
                                    })
                                    setModal(true)
                                 }}
                              />
                           );
                        })
                        :
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada tugas</Text>
               }
            </View>
         </View>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={setModal} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="clock-time-three-outline"
                        color={colors.text}
                        size={25}
                     />
                  }
                  title="Detail Waktu"
                  onPress={() => {
                     setModal(false);
                     setTimeout(() => {
                        setModalDetail(true)
                     }, 600)
                  }}
               />
               {
                  (entityUser.role != "user" && entityUser.role != "coadmin") || isMemberDivision
                     ?
                     <>
                        <MenuItemRow
                           icon={<MaterialCommunityIcons name="list-status" color={colors.text} size={25} />}
                           title="Update Status"
                           onPress={() => {
                              setModal(false)
                              setTimeout(() => {
                                 setSelect(true)
                              }, 600);
                           }}
                        />
                        <MenuItemRow
                           icon={<MaterialCommunityIcons name="pencil-outline" color={colors.text} size={25} />}
                           title="Edit Tugas"
                           onPress={() => {
                              setModal(false)
                              router.push(`./update/${tugas.id}`)
                           }}
                        />
                     </>
                     :
                     <></>
               }

            </View>
            {
               (entityUser.role != "user" && entityUser.role != "coadmin") || isMemberDivision
                  ?
                  <View style={[Styles.rowItemsCenter, Styles.mt15]}>
                     <MenuItemRow
                        icon={<Ionicons name="trash" color={colors.text} size={25} />}
                        title="Hapus Tugas"
                        onPress={() => {
                           setModal(false)
                           AlertKonfirmasi({
                              title: 'Konfirmasi',
                              desc: 'Apakah anda yakin ingin menghapus data ini?',
                              onPress: () => {
                                 handleDelete()
                              }
                           })

                        }}
                     />
                  </View>
                  :
                  <></>
            }
         </DrawerBottom>

         <ModalSelect
            category="status-task"
            close={() => setSelect(false)}
            onSelect={(value) => { handleUpdate(Number(value.val)) }}
            title="Status"
            open={isSelect}
            valChoose={String(tugas.status)}
         />

         <ModalListDetailTugasTask
            isVisible={modalDetail}
            setVisible={setModalDetail}
            idTask={tugas.id}
         />
      </>
   )
}