import React, {Fragment, useCallback, useState} from 'react';
import {Pressable, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconChevronRight, IconPlus} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {
  Divider,
  ListSkeleton,
  Skeleton,
  StateCard,
  Typography,
} from '@components';
import {chatMembershipsHandler} from '@config/synchroniser';
import {useGroupInfo, useMembershipSyncState} from '@modules/chats/hooks';
import {Membership} from '@modules/chats/interfaces';
import {SPACING, useTheme} from '@shared/theme';
import {Screens} from '@shared/constants';

import {styles} from './styles';
import MemberItem from '../MemberItem';
import DialogAllMembers from '../DialogAllMembers';
import DialogAddMembers from '../DialogAddMembers';
import DialogMemberActions from '../DialogMemberActions';

interface Props {
  channel: string;
}

export function GroupMembers({channel}: Props) {
  const {t} = useTranslation();
  const {theme, iconSizes, borderRadius} = useTheme();
  const [isAllMembersVisible, setAllMembersVisible] = useState(false);
  const [isAddMembersVisible, setAddMembersVisible] = useState(false);
  const [selectedMember, setSelectedMember] =
    useState<Nullable<Membership>>(null);
  const {totalMembers, isUserAdmin, useSlicedData} = useGroupInfo(channel);
  const {shortGroupMembers, isThereMoreUsers} = useSlicedData(4);
  const syncState = useMembershipSyncState(channel);
  const isProcessed = syncState === 'processed';
  const hasFailed = syncState === 'failed' || syncState === 'cancelled';
  const navigation = useNavigation();

  const onRetry = () => {
    chatMembershipsHandler.addToQueue(channel, 'high');
  };

  const onMoreMembersPress = () => {
    setAllMembersVisible(true);
  };

  const onAddMemberPress = () => {
    setAddMembersVisible(true);
  };

  const onAllMembersDialogClose = () => {
    setAllMembersVisible(false);
  };

  const onAddMembersDialogClose = () => {
    setAddMembersVisible(false);
  };

  const onMemberActionsClose = () => {
    setSelectedMember(null);
  };

  const onMemberActionsPress = useCallback((member: Membership) => {
    setAllMembersVisible(false);
    setSelectedMember(member);
  }, []);

  const onRedirectToProfile = useCallback(
    (userId: number) => {
      navigation.navigate(Screens.PROFILE, {userId});
    },
    [navigation],
  );

  return (
    <>
      {isProcessed ? (
        <View
          style={[
            {
              backgroundColor: theme.background.layout.tertiary,
              borderColor: theme.border.neutral.default,
            },
            styles.listContainer,
          ]}>
          <View style={styles.membersContainer}>
            <Typography variant="s" weight="semiBold">
              {t('chat.groups.members', {
                count: totalMembers,
              })}
            </Typography>
            {isUserAdmin && (
              <Pressable
                onPress={onAddMemberPress}
                style={[
                  {
                    borderRadius: borderRadius.m,
                    borderColor: theme.border.neutral.brand,
                  },
                  styles.addMemberButtonContainer,
                ]}>
                <Typography
                  variant="xs"
                  weight="semiBold"
                  color={theme.text.neutral.brand}
                  style={styles.addText}>
                  {t('general.add')}
                </Typography>
                <IconPlus
                  size={iconSizes.x3}
                  color={theme.text.neutral.brand}
                />
              </Pressable>
            )}
          </View>
          {shortGroupMembers.map((member, index) => {
            const isLastItem = index === shortGroupMembers.length - 1;
            return (
              <Fragment key={member.user.id}>
                <MemberItem
                  membership={member}
                  isUserAdmin={isUserAdmin}
                  onMemberActionsPress={setSelectedMember}
                  onRedirectToProfile={onRedirectToProfile}
                />
                {!isLastItem && <Divider />}
              </Fragment>
            );
          })}
          {isThereMoreUsers && (
            <>
              <Divider />
              <Pressable
                style={styles.moreUsersContainer}
                onPress={onMoreMembersPress}>
                <Typography
                  color={theme.brand[500]}
                  variant="s"
                  weight="semiBold">
                  {t('chat.groups.show_all_members')}
                </Typography>
                <IconChevronRight
                  size={iconSizes.x6}
                  color={theme.brand[500]}
                />
              </Pressable>
            </>
          )}
        </View>
      ) : (
        <View style={styles.errorSkeletonContainer}>
          {hasFailed ? (
            <StateCard
              variant="error"
              title={t('chat.groups.load_again_error')}
              description={t('chat.groups.load_again_subtitle')}>
              <StateCard.Footer>
                <StateCard.Button
                  variant="secondary"
                  text={t('chat.groups.load_again')}
                  onPress={onRetry}
                />
              </StateCard.Footer>
            </StateCard>
          ) : (
            <View
              style={[
                {
                  backgroundColor: theme.background.layout.tertiary,
                  borderColor: theme.border.neutral.default,
                },
                styles.skeletonContainer,
              ]}>
              <Skeleton>
                <Skeleton.Item width="100%" height={SPACING.x3} />
              </Skeleton>
              <ListSkeleton
                presentation="flat"
                withDescription={false}
                style={styles.skeletonListContainer}
                itemLength={5}
              />
            </View>
          )}
        </View>
      )}
      <DialogAllMembers
        channel={channel}
        totalMembers={totalMembers}
        isUserAdmin={isUserAdmin}
        isVisible={isAllMembersVisible}
        onClose={onAllMembersDialogClose}
        onMemberActionsPress={onMemberActionsPress}
      />
      <DialogAddMembers
        channel={channel}
        isVisible={isAddMembersVisible}
        onClose={onAddMembersDialogClose}
      />
      <DialogMemberActions
        channel={channel}
        membership={selectedMember}
        isVisible={!!selectedMember}
        onClose={onMemberActionsClose}
      />
    </>
  );
}
