'use client'
import { funGetAllGroup, IDataGroup } from "@/module/group";
import { Avatar, Box, Button, Divider, Grid, Group, rem, Select, Text, TextInput } from "@mantine/core";
import { useMediaQuery, useShallowEffect } from "@mantine/hooks";
import { useState } from "react";
import toast from "react-hot-toast";
import { IoIosArrowDropright } from "react-icons/io";
import ChooseUsersDiscussion from "./choose_user";
import { useHookstate } from "@hookstate/core";
import { globalRole, keyWibu, LayoutNavbarNew, TEMA } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { globalMemberDiscussionGeneral } from "../lib/val_discussion_general";
import { IFormMemberDisscussionGeneral } from "../lib/type_discussion_general";
import LayoutModal from "@/module/_global/layout/layout_modal";
import { funCreateDiscussionGeneral } from "../lib/api_discussion_general";
import { useRouter } from "next/navigation";
import { useWibuRealtime } from "wibu-realtime";

export default function FormCreateDiscussionGeneral() {
   const router = useRouter()
   const isMobile = useMediaQuery('(max-width: 369px)')
   const roleLogin = useHookstate(globalRole)
   const [isModal, setModal] = useState(false)
   const [dataGroup, setDataGroup] = useState<IDataGroup[]>([])
   const [isChooseAnggota, setChooseAnggota] = useState(false)
   const member = useHookstate(globalMemberDiscussionGeneral)
   const memberValue = member.get() as IFormMemberDisscussionGeneral[]
   const tema = useHookstate(TEMA)
   const [loadingModal, setLoadingModal] = useState(false)
   const [data, setDataRealtime] = useWibuRealtime({
      WIBU_REALTIME_TOKEN: keyWibu,
      project: "sdm"
   })
   const [body, setBody] = useState<any>({
      idGroup: "",
      title: "",
      desc: ""
   });

   const [touched, setTouched] = useState({
      title: false,
      idGroup: false,
      desc: false
   });

   function onToChooseAnggota() {
      if (roleLogin.get() == "supadmin" && body.idGroup == "")
         return toast.error("Error! grup harus diisi")
      setChooseAnggota(true)
   }

   async function loadData() {
      const loadGroup = await funGetAllGroup('?active=true')
      if (loadGroup.success) {
         setDataGroup(loadGroup.data);
      } else {
         toast.error(loadGroup.message);
      }

      if (roleLogin.get() != "supadmin") {
         const loadUser = await funGetUserByCookies();
         setBody({ ...body, idGroup: loadUser.idGroup })
      }
   }

   useShallowEffect(() => {
      loadData();
   }, []);


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

      if (memberValue.length <= 1)
         return toast.error("Error! Silahkan pilih anggota lebih dari 1")

      setModal(true)
   }

   function checkAll() {
      let nilai = true
      if (body.idGroup === "" || String(body.idGroup) == "null") {
         setTouched(touched => ({ ...touched, idGroup: true }))
         nilai = false
      }
      if (body.title === "") {
         setTouched(touched => ({ ...touched, title: true }))
         nilai = false
      }
      if (body.desc === "") {
         setTouched(touched => ({ ...touched, desc: true }))
         nilai = false
      }
      return nilai
   }


   function onValidation(kategori: string, val: string) {
      if (kategori == 'idGroup') {
         setBody({ ...body, idGroup: val })
         if (val === "" || String(val) == "null") {
            setTouched({ ...touched, idGroup: true })
         } else {
            setTouched({ ...touched, idGroup: false })
         }
      } else if (kategori == 'title') {
         setBody({ ...body, title: val })
         if (val === "") {
            setTouched({ ...touched, title: true })
         } else {
            setTouched({ ...touched, title: false })
         }
      } else if (kategori == 'diskusi') {
         setBody({ ...body, desc: val })
         if (val === "") {
            setTouched({ ...touched, desc: true })
         } else {
            setTouched({ ...touched, desc: false })
         }
      }
   }

   function onChooseGroup(val: any) {
      member.set([])
      onValidation('idGroup', val)
   }

   async function onSubmit() {
      try {
         setLoadingModal(true)
         const res = await funCreateDiscussionGeneral({ idGroup: body.idGroup, title: body.title, desc: body.desc, member: memberValue })
         if (res.success) {
            setDataRealtime(res.notif)
            member.set([])
            toast.success(res.message)
            router.push('/discussion')
         } else {
            toast.error(res.message)
         }
      } catch (error) {
         console.error(error)
         toast.error("Gagal membuat diskusi umum, coba lagi nanti")
      } finally {
         setLoadingModal(false)
         setModal(false)
      }
   }

   if (isChooseAnggota) return <ChooseUsersDiscussion grup={body.idGroup} onClose={() => setChooseAnggota(false)} />

   return (
      <Box>
         <LayoutNavbarNew back="" title="Tambah Diskusi Umum" menu={<></>} />
         <Box p={20}>
            <Box>
               {
                  (roleLogin.get() == "supadmin") && (
                     <Select
                        placeholder="Grup"
                        label="Grup"
                        size="md"
                        styles={{
                           input: {
                              border: `1px solid ${"#D6D8F6"}`,
                              borderRadius: 10,
                           },
                        }}
                        required
                        data={dataGroup?.map((pro: any) => ({
                           value: String(pro.id),
                           label: pro.name
                        }))}
                        onChange={(val) => {
                           onChooseGroup(val)
                        }}
                        value={(body.idGroup == "") ? null : body.idGroup}
                        error={
                           touched.idGroup && (
                              body.idGroup == "" || String(body.idGroup) == "null" ? "Grup Tidak Boleh Kosong" : null
                           )
                        }
                     />
                  )
               }

               <TextInput
                  label="Judul"
                  styles={{
                     input: {
                        border: `1px solid ${"#D6D8F6"}`,
                        borderRadius: 10,
                     },
                  }}
                  mt={10}
                  required withAsterisk
                  placeholder="Judul"
                  size="md"
                  value={body.title}
                  onChange={(e) => { onValidation('title', e.target.value) }}
                  error={
                     touched.title && (
                        body.title == "" ? "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={body.desc}
                  onChange={(e) => { onValidation('diskusi', e.target.value) }}
                  error={
                     touched.desc && (
                        body.desc == "" ? "Diskusi Tidak Boleh Kosong" : null
                     )
                  }
               />
               <Box mt={15}>
                  <Group
                     onClick={() => onToChooseAnggota()}
                     justify="space-between"
                     p={10}
                     style={{
                        border: `1px solid ${"#D6D8F6"}`,
                        borderRadius: 10,
                     }}
                  >
                     <Text>Pilih Anggota</Text>
                     <IoIosArrowDropright size={25} />
                  </Group>
               </Box>
            </Box>
            <Box pb={100}>
               {
                  member.length > 0 &&
                  <Box pt={30}>
                     <Group justify="space-between">
                        <Text c={tema.get().utama}>Anggota Terpilih</Text>
                        <Text c={tema.get().utama}>Total {member.length} Anggota</Text>
                     </Group>
                     <Box pt={10}>
                        <Box mb={20}>
                           <Box
                              style={{
                                 border: `1px solid ${"#C7D6E8"}`,
                                 borderRadius: 10,
                              }}
                              px={20}
                              py={10}
                           >
                              {member.get().map((v: any, i: any) => {
                                 return (
                                    <Box key={i}>
                                       <Grid align='center' mt={10} >
                                          <Grid.Col span={9}>
                                             <Group>
                                                <Avatar src={`https://wibu-storage.wibudev.com/api/files/${v.img}`} alt="it's me" size={isMobile ? 'md' : 'lg'} />
                                                <Box w={{
                                                   base: isMobile ? 130 : 140,
                                                   xl: 270
                                                }}>
                                                   <Text c={tema.get().utama} fw={"bold"} lineClamp={1} fz={isMobile ? 14 : 16}>
                                                      {v.name}
                                                   </Text>
                                                </Box>
                                             </Group>
                                          </Grid.Col>
                                          <Grid.Col span={3}>
                                             <Text c={tema.get().utama} fw={"bold"} ta={'end'} fz={isMobile ? 13 : 16}>
                                                Anggota
                                             </Text>
                                          </Grid.Col>
                                       </Grid>
                                       <Box mt={10}>
                                          <Divider size={"xs"} />
                                       </Box>
                                    </Box>
                                 );
                              })}
                           </Box>
                        </Box>
                     </Box>
                  </Box>
               }
            </Box>
         </Box>
         <Box pos={'fixed'} bottom={0} p={rem(20)} w={"100%"} style={{
            maxWidth: rem(550),
            zIndex: 999,
            backgroundColor: `${tema.get().bgUtama}`,
         }}>
            <Button
               color="white"
               bg={tema.get().utama}
               size="lg"
               radius={30}
               fullWidth
               onClick={() => { onCheck() }}>
               Simpan
            </Button>
         </Box>


         <LayoutModal loading={loadingModal} opened={isModal} onClose={() => setModal(false)}
            description="Apakah Anda yakin ingin menambahkan data?"
            onYes={(val) => {
               if (val) {
                  onSubmit()
               } else {
                  setModal(false)
               }
            }} />
      </Box>
   )
}