import React, {useState} from 'react';
import {ScrollView, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {IconEdit} from '@tabler/icons-react-native';
import {BackButton, IconButton, Title} from '@components';
import {Navigation} from '@interfaces/navigation';
import {
  useConversation,
  useIsUserAdminOfVisibleChat,
} from '@modules/chats/store';
import {useTheme} from '@shared/theme';
import {Screens} from '@shared/constants';

import {styles} from './styles';
import {GroupInfo} from './components/GroupInfo';
import {ImInfo} from './components/ImInfo';
import {DialogEditGroup} from './components/DialogEditGroup';

export function ChatInfoScreen({
  navigation,
  route,
}: Navigation<Screens.CHATS_CHAT_INFO>) {
  const {id} = route.params;
  const {t} = useTranslation();
  const conversation = useConversation(id);
  const isUserAdmin = useIsUserAdminOfVisibleChat();
  const {spacing, theme} = useTheme();
  const {top, bottom} = useSafeAreaInsets();
  const [showEditGroupDialog, setShowEditGroupDialog] = useState(false);
  const isGroup = conversation?.is_channel;

  const onEditGroup = () => {
    setShowEditGroupDialog(true);
  };

  const onCloseEditGroupDialog = () => {
    setShowEditGroupDialog(false);
  };

  return (
    <>
      <View
        style={[
          styles.container,
          !!top && {paddingTop: top},
          {backgroundColor: theme.background.layout.tertiary},
        ]}>
        <View
          style={[
            styles.header,
            {
              borderColor: theme.border.neutral.default,
            },
          ]}>
          <View style={styles.backButtonContainer}>
            <BackButton onPress={navigation.goBack} />
          </View>
          <Title
            title={t(isGroup ? 'chat.groups.group_info' : 'chat.im_info')}
            center
          />
          {isUserAdmin && (
            <View style={styles.editButtonContainer}>
              <IconButton
                Icon={IconEdit}
                onPress={onEditGroup}
                variant="tertiary"
              />
            </View>
          )}
        </View>
        <View
          style={[
            styles.contentContainer,
            {backgroundColor: theme.background.layout.default},
          ]}>
          <ScrollView
            contentContainerStyle={[
              styles.scrollView,
              !!bottom && {paddingBottom: bottom + spacing.x2},
            ]}>
            {isGroup ? <GroupInfo channel={id} /> : <ImInfo channel={id} />}
          </ScrollView>
        </View>
      </View>
      <DialogEditGroup
        channel={id}
        isVisible={showEditGroupDialog}
        onClose={onCloseEditGroupDialog}
      />
    </>
  );
}
