"use client"
import { keyWibu, LayoutNavbarNew, TEMA } from '@/module/_global';
import LayoutModal from '@/module/_global/layout/layout_modal';
import { useHookstate } from '@hookstate/core';
import { Box, Button, rem, Skeleton, Stack, Textarea } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { useWibuRealtime } from 'wibu-realtime';
import { funEditReportTask, funGetTaskDivisionById } from '../lib/api_task';

export default function AddReportTask() {
   const router = useRouter()
   const [report, setReport] = useState("")
   const [openModal, setOpenModal] = useState(false)
   const param = useParams<{ id: string, detail: string }>()
   const [loading, setLoading] = useState(true)
   const [loadingSubmit, setLoadingSubmit] = useState(false)
   const tema = useHookstate(TEMA)
   const [touched, setTouched] = useState({
      report: false,
   });
   const [dataRealTime, setDataRealtime] = useWibuRealtime({
      WIBU_REALTIME_TOKEN: keyWibu,
      project: "sdm"
   })

   async function onSubmit() {
      try {
         setLoadingSubmit(true)
         const res = await funEditReportTask(param.detail, { report })
         if (res.success) {
            setDataRealtime([{
               category: "tugas-detail-report",
               id: param.detail,
            }])
            toast.success(res.message)
            router.push("./")
         } else {
            toast.error(res.message)
         }
      } catch (error) {
         console.error(error)
         toast.error("Gagal mengedit Laporan Kegiatan, coba lagi nanti")
      } finally {
         setLoadingSubmit(false)
         setOpenModal(false)
      }
   }

   function onCheck() {
      if (report == "") {
         setTouched({ ...touched, report: true })
         return false
      }
      setOpenModal(true)
   }



   function onValidation(kategori: string, val: string) {
      if (kategori == 'report') {
         setReport(val)
         if (val === "") {
            setTouched({ ...touched, report: true })
         } else {
            setTouched({ ...touched, report: false })
         }
      }
   }

   async function getOneData() {
      try {
         setLoading(true)
         const res = await funGetTaskDivisionById(param.detail, 'data');
         if (res.success) {
            setReport(res.data.report);
         } else {
            toast.error(res.message);
         }
      } catch (error) {
         console.error(error);
         toast.error("Gagal mendapatkan data Tugas, coba lagi nanti");
      } finally {
         setLoading(false);
      }
   }

   useShallowEffect(() => {
      getOneData();
   }, [param.detail])


   return (
      <Box >
         <LayoutNavbarNew back="" title={"Laporan Kegiatan"} menu />
         <Box p={20}>
            <Stack pt={15}>
               {loading ?
                  <Skeleton height={150} mt={20} radius={10} />
                  :
                  <Textarea placeholder="Laporan Kegiatan" label="Laporan Kegiatan" size="md" radius={10}
                     value={report}
                     required
                     error={
                        touched.report && (
                           report == "" ? "Laporan Tidak Boleh Kosong" : null
                        )
                     }
                     onChange={(e) => { onValidation('report', e.currentTarget.value) }}
                     styles={{
                        input: {
                           height: "30vh"
                        }
                     }}
                  />
               }
            </Stack>
         </Box>
         <Box pos={'fixed'} bottom={0} p={rem(20)} w={"100%"} style={{
            maxWidth: rem(550),
            zIndex: 999,
            backgroundColor: `${tema.get().bgUtama}`,
         }}>
            {loading ?
               <Skeleton height={50} radius={30} />
               :
               <Button
                  c={"white"}
                  bg={Object.values(touched).some((v) => v == true) || report == "" || report == null ? 'gray' : tema.get().utama}
                  size="lg"
                  radius={30}
                  fullWidth
                  onClick={() => { onCheck() }}
                  disabled={Object.values(touched).some((v) => v == true) || report == "" || report == null ? true : false}
               >
                  Simpan
               </Button>
            }
         </Box>


         <LayoutModal opened={openModal} loading={loadingSubmit} onClose={() => setOpenModal(false)}
            description="Apakah Anda yakin ingin mengedit Laporan Kegiatan ini?"
            onYes={(val) => {
               if (val) {
                  onSubmit()
               } else {
                  setOpenModal(false)
               }
            }} />
      </Box>
   );
}

