'use client'
import { keyWibu, TEMA } from "@/module/_global"
import LayoutModal from "@/module/_global/layout/layout_modal"
import { useHookstate } from "@hookstate/core"
import { Box, Button, rem, Skeleton, TextInput } 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 { funEditDiscussionGeneral, funGetOneDiscussionGeneral } from "../lib/api_discussion_general"

export default function FormEditDiscussionGeneral() {
   const [isValModal, setValModal] = useState(false)
   const [loadingModal, setLoadingModal] = useState(false)
   const router = useRouter()
   const param = useParams<{ id: string }>()
   const [isDesc, setDesc] = useState("")
   const [isTitle, setTitle] = useState("")
   const [loading, setLoading] = useState(true)
   const tema = useHookstate(TEMA)
   const [touched, setTouched] = useState({
      title: false,
      desc: false,
   });
   const [dataRealTime, setDataRealtime] = useWibuRealtime({
      WIBU_REALTIME_TOKEN: keyWibu,
      project: "sdm"
   })

   async function fetchGetOneDiscussion() {
      try {
         setLoading(true)
         const response = await funGetOneDiscussionGeneral(param.id, '?cat=detail')
         setDesc(response.data.desc)
         setTitle(response.data.title)
      } catch (error) {
         console.error(error);
         toast.error("Gagal menampilkan diskusi, coba lagi nanti");
      } finally {
         setLoading(false)
      }
   }

   async function fetchEditDiscussion() {
      try {
         setLoadingModal(true)
         const response = await funEditDiscussionGeneral(param.id, {
            title: isTitle,
            desc: isDesc
         })
         if (response.success) {
            toast.success(response.message)
            setValModal(false)
            setDataRealtime([{
               category: "discussion-general-detail",
               id: param.id,
            }])
            router.push(`/discussion/${param.id}`)
         } else {
            toast.error(response.message)
         }

      } catch (error) {
         console.error(error);
         setValModal(false)
         toast.error("Gagal mengubah diskusi umum, coba lagi nanti");
      } finally {
         setValModal(false)
         setLoadingModal(false)
      }
   }

   useShallowEffect(() => {
      fetchGetOneDiscussion()
   }, [])

   function onValidation(kategori: string, val: string) {
      if (kategori == 'title') {
         setTitle(val)
         if (val === "") {
            setTouched({ ...touched, title: true })
         } else {
            setTouched({ ...touched, title: false })
         }
      } else if (kategori == 'diskusi') {
         setDesc(val)
         if (val === "") {
            setTouched({ ...touched, desc: true })
         } else {
            setTouched({ ...touched, desc: false })
         }
      }
   }


   function onCheck() {
      const cek = checkAll()
      if (!cek)
         return false

      setValModal(true)
   }

   function checkAll() {
      let nilai = true
      if (isTitle === "") {
         setTouched(touched => ({ ...touched, title: true }))
         nilai = false
      }
      if (isDesc === "") {
         setTouched(touched => ({ ...touched, desc: true }))
         nilai = false
      }
      return nilai
   }



   return (
      <Box >
         <Box p={20}>
            <Box>
               {loading ?
                  Array(2)
                     .fill(null)
                     .map((_, i) => (
                        <Skeleton key={i} height={40} mt={20} radius={10} />
                     ))
                  :
                  <Box>
                     <TextInput
                        label="Judul"
                        styles={{
                           input: {
                              border: `1px solid ${"#D6D8F6"}`,
                              borderRadius: 10,
                           },
                        }}
                        mt={10}
                        required withAsterisk
                        placeholder="Judul"
                        size="md"
                        value={isTitle}
                        onChange={(e) => { onValidation('title', e.target.value) }}
                        error={
                           touched.title && (
                              isTitle == "" ? "Judul Tidak Boleh Kosong" : null
                           )
                        }
                     />
                     <TextInput
                        label="Diskusi"
                        styles={{
                           input: {
                              border: `1px solid ${"#D6D8F6"}`,
                              borderRadius: 10,
                           },
                        }}
                        mt={10}
                        required withAsterisk
                        placeholder="Hal yg akan didiskusikan"
                        size="md"
                        value={isDesc}
                        onChange={(e) => { onValidation('diskusi', e.target.value) }}
                        error={
                           touched.desc && (
                              isDesc == "" ? "Diskusi Tidak Boleh Kosong" : null
                           )
                        }
                     />
                  </Box>
               }
            </Box>
         </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
                  color="white"
                  bg={tema.get().utama}
                  size="lg"
                  radius={30}
                  fullWidth
                  onClick={() => { onCheck() }}
               >
                  Simpan
               </Button>
            }
         </Box>

         <LayoutModal loading={loadingModal} opened={isValModal} onClose={() => setValModal(false)}
            description="Apakah Anda yakin ingin mengubah data?"
            onYes={(val) => {
               if (val) {
                  fetchEditDiscussion()
               } else {
                  setValModal(false)
               }
            }} />
      </Box>
   )
}