"use client"
import { LayoutNavbarNew, SkeletonList, TEMA } from '@/module/_global';
import LayoutModal from '@/module/_global/layout/layout_modal';
import { funGetUserByCookies } from '@/module/auth';
import { funGetAllmember, TypeUser } from '@/module/user';
import { useHookstate } from '@hookstate/core';
import { Carousel } from '@mantine/carousel';
import { ActionIcon, Avatar, Box, Button, Center, Divider, Flex, Grid, Indicator, rem, Stack, Text, TextInput } from '@mantine/core';
import { useMediaQuery, useShallowEffect } from '@mantine/hooks';
import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { FaCheck } from 'react-icons/fa6';
import { HiMagnifyingGlass } from 'react-icons/hi2';
import { IoArrowBackOutline, IoClose } from 'react-icons/io5';
import { funAddMemberDiscussionGeneral, funGetOneDiscussionGeneral } from '../lib/api_discussion_general';
import { IFormMemberDisscussionGeneral } from '../lib/type_discussion_general';



export default function AddMemberDiscussionGeneral() {
  const router = useRouter()
  const [selectedFiles, setSelectedFiles] = useState<IFormMemberDisscussionGeneral[]>([]);
  const [dataMember, setDataMember] = useState<TypeUser>([])
  const [memberDb, setMemberDb] = useState<any[]>([])
  const [group, setGroup] = useState("")
  const [isOpen, setOpen] = useState(false)
  const param = useParams<{ id: string }>()
  const [loading, setLoading] = useState(true)
  const [onClickSearch, setOnClickSearch] = useState(false)
  const tema = useHookstate(TEMA)
  const isMobile2 = useMediaQuery("(max-width: 438px)")
  const [loadingModal, setLoadingModal] = useState(false)

  const handleFileClick = (index: number) => {
    if (selectedFiles.some((i: any) => i.idUser == dataMember[index].id)) {
      setSelectedFiles(selectedFiles.filter((i: any) => i.idUser != dataMember[index].id))
    } else {
      setSelectedFiles([...selectedFiles, { idUser: dataMember[index].id, name: dataMember[index].name, img: dataMember[index].img }])
    }
  };

  function handleXMember(id: number) {
    setSelectedFiles(selectedFiles.filter((i: any) => i.idUser != id))
  }


  async function loadMember(group: string, search: string) {
    try {
      setLoading(true)
      const res = await funGetAllmember('?active=true&group=' + group + '&search=' + search);
      const user = await funGetUserByCookies();

      if (res.success) {
        // const dariUserLogin = res.data.filter((i: any) => i.id != user.id)
        // const fixListUser = dariUserLogin.filter((i: any) => i.idUserRole == 'coadmin' || i.idUserRole == 'user')
        const fixListUser = res.data.filter((i: any) => i.idUserRole != 'supadmin')
        setDataMember(fixListUser)
      } else {
        toast.error(res.message)
      }
    } catch (error) {
      console.error(error)
      toast.error("Gagal memuat data, coba lagi nanti")
    } finally {
      setLoading(false)
    }

  }

  async function loadFirst() {
    const respon = await funGetOneDiscussionGeneral(param.id, '?cat=detail');
    const respon2 = await funGetOneDiscussionGeneral(param.id, '?cat=anggota');
    if (respon.success) {
      setGroup(respon.data.idGroup)
      setMemberDb(respon2.data)
      loadMember(respon.data.idGroup, "")
    } else {
      toast.error(respon.message);
    }
  }

  async function addMember() {
    try {
      setLoadingModal(true)
      const res = await funAddMemberDiscussionGeneral(param.id, { member: selectedFiles })
      if (res.success) {
        toast.success(res.message)
        router.push("/discussion/" + param.id + "/member")
      } else {
        toast.error(res.message)
      }
    } catch (error) {
      console.error(error);
      toast.error("Gagal menambahkan anggota diskusi umum, coba lagi nanti");
    } finally {
      setLoadingModal(false)
      setOpen(false)
    }
  }

  function onCheck() {
    if (selectedFiles.length == 0) {
      return toast.error("Error! silahkan pilih anggota")
    }
    setOpen(true)
  }


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

  const handleSearchClick = () => {
    setOnClickSearch(true);
  };

  const handleClose = () => {
    setOnClickSearch(false);
  };

  return (
    <Box>
      <LayoutNavbarNew back={`/discussion/${param.id}/member`} title="tambah anggota"
        menu={<ActionIcon onClick={handleSearchClick} variant="light" bg={tema.get().bgIcon} size="lg" radius="lg" aria-label="search">
          <HiMagnifyingGlass size={20} color='white' />
        </ActionIcon>}
      />
      {onClickSearch
        ? (
          <Box
            pos={'fixed'} top={0} p={rem(20)} w={"100%"} style={{
              maxWidth: rem(550),
              zIndex: 9999,
              backgroundColor: `${tema.get().utama}`,
              borderBottomLeftRadius: 20,
              borderBottomRightRadius: 20,
            }}>
            <Grid justify='center' align='center' gutter={'lg'}>
              <Grid.Col span={1}>
                <ActionIcon onClick={handleClose} variant="subtle" color='white' size="lg" mt={5} radius="lg" aria-label="search">
                  <IoArrowBackOutline size={30} />
                </ActionIcon>
              </Grid.Col>
              <Grid.Col span={11}>
                <TextInput
                  styles={{
                    input: {
                      color: "white",
                      borderRadius: '#A3A3A3',
                      borderColor: `${tema.get().utama}`,
                      backgroundColor: `${tema.get().utama}`,
                    },
                  }}
                  size="md"
                  radius={30}
                  placeholder="Pencarian"
                  onChange={(e: any) => loadMember(group, e.target.value)}
                />
              </Grid.Col>
            </Grid>
          </Box>
        )
        : null
      }
      <Box pos={'fixed'} top={80} pl={rem(20)} pr={rem(20)} pt={rem(20)} pb={rem(5)} w={"100%"} style={{
        maxWidth: rem(550),
        zIndex: 100,
        backgroundColor: `${tema.get().bgUtama}`,
        borderBottom: `1px solid ${"#E0DFDF"}`
      }}>
        {selectedFiles.length > 0 ? (
          <Carousel dragFree slideGap={"xs"} align="start" slideSize={"xs"} withControls={false}>
            {selectedFiles.map((v: any, i: any) => {
              return (
                <Carousel.Slide key={i}>
                  <Box w={{
                    base: 70,
                    xl: 70
                  }}
                    onClick={() => { handleXMember(v.idUser) }}
                  >
                    <Center>
                      <Indicator inline size={25} offset={7} position="bottom-end" color="red" withBorder label={<IoClose />}>
                        <Avatar style={{
                          border: `2px solid ${tema.get().utama}`
                        }} src={`https://wibu-storage.wibudev.com/api/files/${v.img}`} alt="it's me" size="lg" />
                      </Indicator>
                    </Center>
                    <Text ta={"center"} lineClamp={1}>{v.name}</Text>
                  </Box>
                </Carousel.Slide>
              )
            })}
          </Carousel>
        ) : (
          <Box h={rem(81)}>
            <Flex justify={"center"} align={'center'} h={"100%"}>
              <Text ta={'center'} fz={14}>Tidak ada anggota yang dipilih</Text>
            </Flex>
          </Box>
        )}
      </Box>
      <Box p={20}>
        {loading ?
          Array(8)
            .fill(null)
            .map((_, i) => (
              <Box key={i}>
                <SkeletonList />
              </Box>
            ))
          :
          (dataMember.length === 0) ?
            <Stack align="stretch" justify="center" w={"100%"} h={"60vh"}>
              <Text c="dimmed" ta={"center"} fs={"italic"}>Tidak ada anggota</Text>
            </Stack>
            :
            <Box pt={90} mb={100}>
              {dataMember.map((v: any, index: any) => {
                const isSelected = selectedFiles.some((i: any) => i.idUser == dataMember[index].id)
                const found = memberDb.some((i: any) => i.idUser == v.id)
                return (
                  <Box my={10} key={index} onClick={() => (!found) ? handleFileClick(index) : null}>
                    <Grid align='center' >
                      <Grid.Col
                        span={{
                          base: 1,
                          xs: 1,
                          sm: 1,
                          md: 1,
                          lg: 1,
                          xl: 1,
                        }}
                      >
                        <Avatar src={`https://wibu-storage.wibudev.com/api/files/${v.img}`} alt="it's me" size="lg" />
                      </Grid.Col>
                      <Grid.Col
                        span={{
                          base: 11,
                          xs: 11,
                          sm: 11,
                          md: 11,
                          lg: 11,
                          xl: 11,
                        }}
                      >
                        <Flex justify='space-between' align={"center"}>
                          <Flex direction={'column'} align="flex-start" justify="flex-start">
                            <Text pl={isMobile2 ? 40 : 30} lineClamp={1}>{v.name}</Text>
                            <Text pl={isMobile2 ? 40 : 30} c={"dimmed"} lineClamp={1}>{(found) ? "sudah menjadi anggota divisi" : ""}</Text>
                          </Flex>
                          {isSelected ? <FaCheck /> : null}
                        </Flex>
                      </Grid.Col>
                    </Grid>
                    <Box mt={10}>
                      <Divider size={"xs"} />
                    </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={isOpen} onClose={() => setOpen(false)}
        description="Apakah Anda yakin ingin menambahkan anggota diskusi umum?"
        onYes={(val) => {
          if (val) {
            addMember()
          } else {
            setOpen(false)
          }
        }} />
    </Box>
  );
}
