import { type FC, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import {
  IconChevronRight,
  IconEdit,
  IconLogout,
  IconPlus,
  IconUsersGroup,
  IconX,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Drawer from '@material-hu/mui/Drawer';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import { useAuth } from 'src/contexts/JWTContext';
import {
  BUNNY_IMAGE_CLASSES,
  CONVERSATIONS_GORUP_INFO_ID,
} from 'src/pages/dashboard/Conversations/constants';
import {
  type Channel,
  type Member,
} from 'src/pages/dashboard/Conversations/types';
import { getMembersToShow } from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import Scrollbar from 'src/components/Scrollbar';

import LazySecureImage from '../../shared/LazySecureImage';

import AddMembers from './ConversationsEdit/AddMembers';
import EditDescriptionButton from './ConversationsEdit/EditDescriptionButton';
import EditGroupInfo from './ConversationsEdit/EditGroupInfo';
import LeaveGroup from './ConversationsEdit/LeaveGroup';
import MembersList from './MembersList';
import ShowAllMembers from './ShowAllMembers';

type GroupInfoType = {
  openGroupInfo: boolean;
  onCloseGroupInfo: () => void;
  conversation: Channel | undefined;
  members: Member[];
};
const MIN_ADMINS = 1;
const GroupInfo: FC<GroupInfoType> = props => {
  const { openGroupInfo, onCloseGroupInfo, conversation, members } = props;
  const [open, setOpen] = useState(false);
  const { id } = useParams();
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const { user } = useAuth();
  const theme = useTheme();

  useEffect(() => {
    return () => {
      if (openGroupInfo) {
        onCloseGroupInfo();
      }
    };
  }, [id, openGroupInfo]);

  const {
    modal: editGroupInfoModal,
    showModal: showEditGroupInfoModal,
    closeModal,
  } = useModal(
    EditGroupInfo,
    { fullWidth: true, maxWidth: 'sm' },
    {
      conversation,
      onClose: () => closeModal(),
      title: t('chat:groups.manage.edit_info'),
    },
  );

  const { count: adminCount, isAdmin } = members.reduce<{
    count: number;
    isAdmin: boolean;
  }>(
    (acc, m) => ({
      count: acc.count + (m.is_admin ? 1 : 0),
      isAdmin: acc.isAdmin || (m.id === user?.id && !!m.is_admin),
    }),
    { count: 0, isAdmin: false },
  );
  const areManyAdmins = adminCount > MIN_ADMINS;
  const canLeaveGroup = (isAdmin && areManyAdmins) || !isAdmin;
  const {
    modal: leaveGroupInfoModal,
    showModal: showLeaveGroupInfoModal,
    closeModal: closeModalLeaveGroup,
  } = useModal(
    LeaveGroup,
    { fullWidth: true, maxWidth: 'sm' },
    {
      onClose: () => closeModalLeaveGroup(),
      title: canLeaveGroup
        ? t('chat:groups.leave_group_question', { name: conversation?.name })
        : t('chat:groups.manage.you_admin_title'),
      description: canLeaveGroup
        ? t('chat:groups.leave_group_description')
        : t('chat:groups.manage.you_admin_description'),
      channelId: conversation?.id,
      primaryTextButton: canLeaveGroup
        ? t('general:exit')
        : t('chat:groups.go_back_chat'),
      userId: user?.id,
      userName: `${user?.firstName} ${user?.lastName}`,
      canLeaveGroup,
    },
  );

  const {
    modal: addMembersModal,
    showModal: showAddMembersModal,
    closeModal: closeAddMembersModal,
  } = useModal(
    AddMembers,
    { fullWidth: true, maxWidth: 'sm' },
    {
      onClose: () => closeAddMembersModal(),
      title: t('chat:groups.create.add_members'),
      channelId: conversation?.id,
      membersToExclude: members
        .filter(elem => !elem.deleted_at)
        .map(elem => elem.id),
    },
  );

  const handleOpenAllMembers = () => setOpen(true);

  const handleCloseAllMembers = () => setOpen(false);

  const showAllMembers = members.length > 5;

  const membersToShow = getMembersToShow(showAllMembers, members, user?.id);

  return (
    <Drawer
      variant="persistent"
      anchor="right"
      open={openGroupInfo}
      transitionDuration={0}
      onClose={onCloseGroupInfo}
      id={CONVERSATIONS_GORUP_INFO_ID}
      PaperProps={{
        sx: {
          width: openGroupInfo ? 360 : 0,
          backgroundColor: theme.palette.new.background.layout.tertiary,
        },
      }}
      sx={{
        width: openGroupInfo ? 360 : 0,
        willChange: openGroupInfo ? 'transform' : 'unset',
      }}
    >
      <Stack
        sx={{ p: 2, flexDirection: 'row', justifyContent: 'space-between' }}
      >
        <Typography
          variant="globalM"
          fontWeight="fontWeightSemiBold"
        >
          {t('chat:groups.group_info')}
        </Typography>
        <IconX
          style={{ cursor: 'pointer' }}
          onClick={onCloseGroupInfo}
        />
      </Stack>
      <Stack sx={{ flex: 1, overflow: 'hidden' }}>
        <Scrollbar>
          <Stack sx={{ alignItems: 'center' }}>
            <Stack sx={{ alignItems: 'center', mt: 2, position: 'relative' }}>
              {isAdmin && (
                <IconButton
                  onClick={() => showEditGroupInfoModal()}
                  variant="secondary"
                  sx={{ position: 'absolute', top: 0, right: 0 }}
                >
                  <IconEdit />
                </IconButton>
              )}
              <Stack
                sx={{
                  height: 128,
                  width: 128,
                  mt: 3,
                  mb: 2,
                  borderRadius: '50%',
                  p: 0,
                  position: 'relative',
                  justifyContent: 'center',
                  alignItems: 'center',
                  backgroundColor: theme.palette.new.background.layout.default,
                  '& img': {
                    width: '100%',
                    height: '100%',
                    borderRadius: '50%',
                    objectFit: 'cover',
                  },
                }}
              >
                {!conversation?.hu_data?.picture_url ? (
                  <IconUsersGroup
                    size={48}
                    color={theme.palette.new.text.neutral.default}
                  />
                ) : (
                  <LazySecureImage
                    url={conversation?.hu_data?.picture_url}
                    imageClass={BUNNY_IMAGE_CLASSES.AVATAR_LG}
                  />
                )}
              </Stack>
              <Typography
                sx={{
                  textAlign: 'center',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  width: 300,
                }}
                variant="globalM"
                fontWeight="fontWeightSemiBold"
              >
                {conversation?.name}
              </Typography>
              <EditDescriptionButton
                isAdmin={isAdmin}
                conversation={conversation}
              />
              <HuCardContainer sx={{ mt: 2, mb: 1 }}>
                <Stack
                  sx={{
                    mb: 2,
                    flexDirection: 'row',
                    width: '100%',
                    gap: 1,
                    alignItems: 'center',
                  }}
                >
                  <Stack sx={{ width: 'inherit' }}>
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        width: 'inherit',
                      }}
                    >
                      <Typography
                        variant="globalM"
                        fontWeight="fontWeightSemiBold"
                        sx={{ textAlign: 'start' }}
                      >
                        {t('chat:groups.members', {
                          count: conversation?.num_members,
                        })}
                      </Typography>
                      {isAdmin && (
                        <Button
                          onClick={() => showAddMembersModal()}
                          endIcon={<IconPlus size={20} />}
                          variant="secondary"
                        >
                          {t('general:add')}
                        </Button>
                      )}
                    </Stack>
                  </Stack>
                </Stack>
                {membersToShow.length >= 1 && <Divider />}
                <MembersList
                  isAdmin={isAdmin}
                  channelId={id || ''}
                  members={membersToShow}
                  userId={user?.id}
                />
                {showAllMembers && (
                  <>
                    <Divider />
                    <Button
                      onClick={handleOpenAllMembers}
                      sx={{
                        mt: 2,
                        justifyContent: 'space-between',
                        width: '100%',
                      }}
                      endIcon={
                        <IconChevronRight
                          style={{
                            stroke: theme.palette.new.graphics.brand[500],
                          }}
                        />
                      }
                    >
                      <Typography
                        variant="globalXS"
                        fontWeight="fontWeightSemiBold"
                        color={theme.palette.new.graphics.brand[500]}
                      >
                        {t('chat:groups.show_all_members')}
                      </Typography>
                    </Button>
                  </>
                )}
              </HuCardContainer>
            </Stack>
            <ShowAllMembers
              open={open}
              isAdmin={isAdmin}
              onClose={handleCloseAllMembers}
              membersCount={conversation?.num_members || 0}
            />
            <HuCardContainer
              sx={{ overflow: 'visible', mb: 2 }}
              onClick={() => showLeaveGroupInfoModal()}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <Stack
                  sx={{
                    flexDirection: 'row',
                    gap: 1,
                    alignItems: 'center',
                  }}
                >
                  <Stack
                    sx={{
                      backgroundColor:
                        theme.palette.new.background.feedback.error,
                      borderRadius: '50%',
                      height: 40,
                      width: 40,
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                  >
                    <IconLogout color={theme.palette.new.text.feedback.error} />
                  </Stack>
                  <Typography
                    variant="globalXS"
                    fontWeight="fontWeightSemiBold"
                  >
                    {t('chat:groups.leave_group')}
                  </Typography>
                </Stack>
                <IconChevronRight
                  color={theme.palette.new.text.neutral.default}
                />
              </Stack>
            </HuCardContainer>
          </Stack>
        </Scrollbar>
      </Stack>
      {addMembersModal}
      {editGroupInfoModal}
      {leaveGroupInfoModal}
    </Drawer>
  );
};

export default GroupInfo;
