import Styles from "@/constants/Styles";
import { apiDeleteProjectTask, apiGetProjectOne, apiUpdateStatusProjectTask } from "@/lib/api";
import { setUpdateProject } from "@/lib/projectUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
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 ModalListDetailTugasProject from "./modalListDetailTugasProject";

type Props = {
   id: string;
   title: string;
   desc: string;
   status: 1;
   dateStart: string;
   dateEnd: string;
   createdAt: string;
};

export default function SectionTanggalTugasProject({ status, member, refreshing }: { status: number | undefined, member: boolean, refreshing?: boolean }) {
   const entityUser = useSelector((state: any) => state.user)
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.projectUpdate)
   const [isModal, setModal] = useState(false);
   const [isSelect, setSelect] = useState(false);
   const { token, decryptToken } = useAuthSession();
   const [modalDetail, setModalDetail] = useState(false)
   const { id } = useLocalSearchParams<{ id: string }>();
   const [data, setData] = useState<Props[]>([]);
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 });
   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 apiGetProjectOne({
            user: hasil,
            cat: "task",
            id: id,
         });
         setData(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

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

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

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


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

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

   return (
      <>
         <View style={[Styles.mb15, Styles.mt10]}>
            <Text style={[Styles.textDefaultSemiBold, Styles.mv05]}>
               Tanggal & Tugas
            </Text>
            <View style={[Styles.wrapPaper]}>
               {
                  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={() => {
                                    if (status == 3 || (!member && (entityUser.role == "user" || entityUser.role == "coadmin"))) return
                                    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="list-status"
                        color="black"
                        size={25}
                     />
                  }
                  title="Update Status"
                  onPress={() => {
                     setModal(false);
                     setTimeout(() => {
                        setSelect(true);
                     }, 600)
                  }}
               />
               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="pencil-outline"
                        color="black"
                        size={25}
                     />
                  }
                  title="Edit Tugas"
                  onPress={() => {
                     setModal(false);
                     router.push(`/project/update/${tugas.id}`);
                  }}
               />

               <MenuItemRow
                  icon={
                     <MaterialCommunityIcons
                        name="clock-time-three-outline"
                        color="black"
                        size={25}
                     />
                  }
                  title="Detail Waktu"
                  onPress={() => {
                     setModal(false);
                     setTimeout(() => {
                        setModalDetail(true)
                     }, 600)
                  }}
               />
            </View>
            <View style={[Styles.rowItemsCenter, Styles.mt15]}>
               <MenuItemRow
                  icon={<Ionicons name="trash" color="black" 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)}
         />

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