'use client'
import { globalRole, keyWibu, LayoutDrawer, LayoutNavbarNew, TEMA } from '@/module/_global';
import LayoutModal from '@/module/_global/layout/layout_modal';
import { funGetUserByCookies } from '@/module/auth';
import { useHookstate } from '@hookstate/core';
import { ActionIcon, Box, Button, Flex, Grid, Modal, SimpleGrid, Stack, Text, 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 { AiFillFileText } from 'react-icons/ai';
import { FaFileCirclePlus, FaPencil, FaTrash, FaUsers } from 'react-icons/fa6';
import { HiMenu } from 'react-icons/hi';
import { IoAddCircle } from 'react-icons/io5';
import { LuLink } from 'react-icons/lu';
import { MdCancel } from 'react-icons/md';
import { useWibuRealtime } from 'wibu-realtime';
import { funAddLinkProject, funDeleteProject, funGetOneProjectById } from '../lib/api_project';
import { globalIsMemberProject } from '../lib/val_project';

export default function NavbarDetailProject() {
  const router = useRouter()
  const param = useParams<{ id: string }>()
  const [name, setName] = useState('')
  const [grup, setGrup] = useState("")
  const [isOpen, setOpen] = useState(false)
  const roleLogin = useHookstate(globalRole)
  const memberProject = useHookstate(globalIsMemberProject)
  const [isUser, setUser] = useState('')
  const tema = useHookstate(TEMA)
  const [reason, setReason] = useState("")
  const [openModal, setOpenModal] = useState(false)
  const [openNewLink, setOpenNewLink] = useState(false)
  const [loadingModal, setLoadingModal] = useState(false)
  const [loadingLink, setLoadingLink] = useState(false)
  const [valLink, setValLink] = useState("")
  const [dataRealTime, setDataRealtime] = useWibuRealtime({
    WIBU_REALTIME_TOKEN: keyWibu,
    project: "sdm"
  })

  async function getOneData() {
    try {
      const res = await funGetOneProjectById(param.id, 'data');
      const userLogin = await funGetUserByCookies()
      if (res.success) {
        setName(res.data.title);
        setReason(res.data.reason);
        setGrup(res.data.idGroup);
        setUser(String(userLogin?.id))
      } else {
        toast.error(res.message);
      }
    } catch (error) {
      console.error(error);
      toast.error("Gagal mendapatkan data kegiatan, coba lagi nanti");
    }
  }

  async function addLinkProject() {
    try {
      setLoadingLink(true)
      const res = await funAddLinkProject(param.id, { link: valLink });
      if (res.success) {
        setDataRealtime([{
          category: "project-detail-link",
          id: param.id,
          user: res.user
        }])
        toast.success(res.message)
      } else {
        toast.error(res.message)
      }
    } catch (error) {
      console.error(error);
      toast.error("Gagal menambahkan link, coba lagi nanti");
    } finally {
      setLoadingLink(false)
      setOpenNewLink(false)
      setValLink("")
    }
  }

  async function deleteDataProject() {
    try {
      setLoadingModal(true)
      const res = await funDeleteProject(param.id);
      if (res.success) {
        setDataRealtime([{
          category: "project-delete",
          id: param.id,
          user: res.user
        }])
        toast.success(res.message)
        router.push("/project")
      } else {
        toast.error(res.message)
      }
    } catch (error) {
      console.error(error);
      toast.error("Gagal menghapus data kegiatan, coba lagi nanti");
    } finally {
      setLoadingModal(false)
      setOpenModal(false)
    }
  }

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

  useShallowEffect(() => {
    if (dataRealTime && dataRealTime.some((i: any) => (i.category == 'project-detail' || i.category == 'project-detail-status') && i.id == param.id)) {
      getOneData()
    }

    if (dataRealTime && dataRealTime.some((i: any) => i.category == 'project-delete' && i.id == param.id && i.user != isUser)) {
      toast.error("Data telah dihapus, anda akan beralih ke halaman list kegiatan")
      setTimeout(() => {
        router.push("/project")
      }, 1000)
    }
  }, [dataRealTime])

  return (
    <>
      <LayoutNavbarNew back={`/project?group=${grup}`} title={name} menu={
        (roleLogin.get() == "user" || roleLogin.get() == "coadmin") && !memberProject.get() ? <></>
          :
          <ActionIcon
            variant="light"
            bg={tema.get().bgIcon}
            size="lg"
            radius="lg"
            aria-label="Settings"
            onClick={() => { setOpen(true) }}
          >
            <HiMenu size={20} color="white" />
          </ActionIcon>
      } />

      <LayoutDrawer opened={isOpen} title={'Menu'} onClose={() => setOpen(false)} size='md'>
        <Box>
          <Stack pt={10}>
            <SimpleGrid
              cols={{ base: 3, sm: 3, lg: 3 }}
              style={{
                alignContent: 'flex-start',
                alignItems: 'flex-start',
              }}
            >
              <Flex justify={'center'} align={'center'} direction={'column'}
                style={{
                  cursor: 'pointer'
                }}
                onClick={() => {
                  reason == null ?
                    router.push(param.id + '/add-task')
                    : null
                }}
                pb={20}
              >
                <Box>
                  <IoAddCircle size={30} color={reason == null ? tema.get().utama : "gray"} />
                </Box>
                <Box>
                  <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Tambah Tugas</Text>
                </Box>
              </Flex>

              <Flex justify={'center'} align={'center'} direction={'column'}
                style={{
                  cursor: 'pointer'
                }}
                onClick={() => {
                  reason == null ?
                    router.push(param.id + '/add-file')
                    : null
                }}
              >
                <Box>
                  <FaFileCirclePlus size={30} color={reason == null ? tema.get().utama : "gray"} />
                </Box>
                <Box>
                  <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Tambah file</Text>
                </Box>
              </Flex>

              <Flex justify={'center'} align={'center'} direction={'column'}
                style={{
                  cursor: 'pointer'
                }}
                onClick={() => {
                  if (reason == null) {
                    setOpen(false)
                    setOpenNewLink(true)
                  } else {
                    null
                  }
                }}
              >
                <Box>
                  <LuLink size={30} color={reason == null ? tema.get().utama : "gray"} />
                </Box>
                <Box>
                  <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Tambah link</Text>
                </Box>
              </Flex>

              <Flex justify={'center'} align={'center'} direction={'column'}
                style={{
                  cursor: 'pointer'
                }}
                onClick={() => {
                  if (reason == null) {
                    router.push(param.id + '/report')
                  } else {
                    null
                  }
                }}
              >
                <Box>
                  <AiFillFileText size={30} color={reason == null ? tema.get().utama : "gray"} />
                </Box>
                <Box>
                  <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Laporan</Text>
                </Box>
              </Flex>

              {
                (roleLogin.get() != "user" && roleLogin.get() != "coadmin") &&
                <>
                  <Flex justify={'center'} align={'center'} direction={'column'}
                    style={{
                      cursor: 'pointer'
                    }}
                    onClick={() => {
                      reason == null ?
                        router.push(param.id + '/add-member')
                        : null
                    }}
                  >
                    <Box>
                      <FaUsers size={30} color={reason == null ? tema.get().utama : "gray"} />
                    </Box>
                    <Box>
                      <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Tambah anggota</Text>
                    </Box>
                  </Flex>

                  <Flex justify={'center'} align={'center'} direction={'column'}
                    style={{
                      cursor: 'pointer'
                    }}
                    onClick={() => {
                      reason == null ?
                        router.push(param.id + '/edit')
                        : null
                    }}
                  >
                    <Box>
                      <FaPencil size={30} color={reason == null ? tema.get().utama : "gray"} />
                    </Box>
                    <Box>
                      <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Edit</Text>
                    </Box>
                  </Flex>
                  {
                    reason == null ?
                      <Flex justify={'center'} align={'center'} direction={'column'} style={{ cursor: 'pointer' }}
                        onClick={() => {
                          reason == null ?
                            router.push(param.id + '/cancel')
                            : null
                        }}
                      >
                        <Box>
                          <MdCancel size={30} color={reason == null ? tema.get().utama : "gray"} />
                        </Box>
                        <Box>
                          <Text c={reason == null ? tema.get().utama : "gray"} ta='center'>Batal</Text>
                        </Box>
                      </Flex>
                      :
                      <Flex justify={'center'} align={'center'} direction={'column'} style={{ cursor: 'pointer' }}
                        onClick={() => { setOpenModal(true) }}
                      >
                        <Box>
                          <FaTrash size={30} color={tema.get().utama} />
                        </Box>
                        <Box>
                          <Text c={tema.get().utama} ta='center'>Hapus</Text>
                        </Box>
                      </Flex>
                  }
                </>
              }

            </SimpleGrid>
          </Stack>
        </Box>
      </LayoutDrawer >

      <LayoutModal loading={loadingModal} opened={openModal} onClose={() => setOpenModal(false)}
        description="Apakah Anda yakin ingin menghapus kegiatan ini?"
        onYes={(val) => { val ? deleteDataProject() : setOpenModal(false) }} />

      <Modal styles={{
        body: {
          borderRadius: 20
        },
        content: {
          borderRadius: 20,
          border: `2px solid ${"#828AFC"}`
        }
      }} opened={openNewLink} onClose={() => setOpenNewLink(false)} centered withCloseButton={false}>
        <Box p={20}>
          <Text ta={"center"} fw={"bold"}>Tambah Link</Text>
          <Box mt={20} mb={20}>
            <TextInput
              styles={{
                input: {
                  color: tema.get().utama,
                  borderRadius: '#828AFC',
                  borderColor: '#828AFC',
                },
              }}
              size="md"
              radius={10}
              placeholder="Masukkan link"
              value={valLink}
              onChange={(e) => setValLink(e.target.value)}
            />
          </Box>
          <Grid mt={40}>
            <Grid.Col span={6}>
              <Button variant="subtle" fullWidth color='#969494' onClick={() => setOpenNewLink(false)}>Batalkan</Button>
            </Grid.Col>
            <Grid.Col span={6}>
              <Button loading={loadingLink} disabled={loadingLink || valLink == "" ? true : false} variant="subtle" fullWidth color={tema.get().utama} onClick={() => { addLinkProject() }}>Tambah</Button>
            </Grid.Col>
          </Grid>
        </Box>
      </Modal>

    </>
  );
}

