import Styles from "@/constants/Styles";
import { apiDeleteTaskTugas, apiGetTaskOne, apiUpdateStatusTaskDivision } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Text, ToastAndroid, View } from "react-native";
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";


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

export default function SectionTanggalTugasTask() {
   const dispatch = useDispatch()
   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 { 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 }))
            ToastAndroid.show("Berhasil mengubah data", ToastAndroid.SHORT);
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT);
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show("Gagal mengubah data", ToastAndroid.SHORT);
      } finally {
         setSelect(false)
      }
   }

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


   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 }))
            ToastAndroid.show("Berhasil menghapus data", ToastAndroid.SHORT);
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT);
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show("Gagal menghapus data", ToastAndroid.SHORT);
      } finally {
         setModal(false);
      }
   }


   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={() => {
                                    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)
                     setSelect(true)
                  }}
               />
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="pencil-outline" color="black" size={25} />}
                  title="Edit Tugas"
                  onPress={() => {
                     setModal(false)
                     router.push(`./update/${tugas.id}`)
                  }}
               />

               <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}
            onSelect={(value) => {
               handleUpdate(Number(value.val))
            }}
            title="Status"
            open={isSelect}
            valChoose={String(tugas.status)}
         />
      </>
   )
}