import React, {useCallback} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconArrowRight, IconPinnedOff} from '@tabler/icons-react-native';
import {Dialog, Divider, Typography} from '@components';
import {Image, Pressable} from '@components/_core';
import {type Message} from '@modules/chats/interfaces';
import {getPinnedCountForChannel} from '@modules/chats/store';
import {useMessagesListMethodsRef} from '@modules/chats/contexts';
import {useTheme} from '@shared/theme';

import {usePinnedMessageDisplay} from '../../hooks/usePinnedMessageDisplay';
import {styles} from './styles';

interface Props {
  channel: string;
  pinned: Message[];
  isVisible: boolean;
  onClose: () => void;
  onUnpin: (clientMsgId: string) => Promise<void>;
  onNavigateToMessage?: (ts: string) => void;
}

function PinnedRow({
  message,
  onUnpin,
  onGoToMessage,
}: {
  message: Message;
  onUnpin: (clientMsgId: string) => Promise<void>;
  onGoToMessage: (ts: string) => void;
}) {
  const {theme, iconSizes} = useTheme();
  const {displayText, PrefixIcon, thumbnailUrl} = usePinnedMessageDisplay({
    message,
  });

  return (
    <View style={styles.row}>
      <View style={styles.rowContent}>
        <View style={styles.rowTextContainer}>
          {PrefixIcon && (
            <PrefixIcon
              color={theme.text.neutral.default}
              size={iconSizes.x6}
            />
          )}
          <Typography
            numberOfLines={1}
            variant="xs"
            weight="semiBold"
            style={[styles.rowContent, {color: theme.text.neutral.default}]}>
            {displayText}
          </Typography>
          {thumbnailUrl ? (
            <Image
              source={{uri: thumbnailUrl}}
              style={styles.thumbnail}
              contentFit="cover"
              withAuthHeader
              timeout={15_000}
            />
          ) : null}
        </View>
      </View>
      <View style={styles.rowActions}>
        <Pressable
          onPress={() => onUnpin(message.client_msg_id)}
          style={styles.rowActionButton}>
          <IconPinnedOff
            size={iconSizes.x6}
            color={theme.text.neutral.default}
          />
        </Pressable>
        <Pressable
          onPress={() => onGoToMessage(message.ts)}
          style={styles.rowActionButton}>
          <IconArrowRight
            size={iconSizes.x6}
            color={theme.text.neutral.default}
          />
        </Pressable>
      </View>
    </View>
  );
}

export function PinnedMessagesSheet({
  channel,
  pinned,
  isVisible,
  onClose,
  onUnpin,
  onNavigateToMessage,
}: Props) {
  const {t} = useTranslation();
  const messagesListMethodsRef = useMessagesListMethodsRef();

  const handleUnpin = useCallback(
    async (clientMsgId: string) => {
      await onUnpin(clientMsgId);
      if (getPinnedCountForChannel(channel) === 0) {
        onClose();
      }
    },
    [channel, onUnpin, onClose],
  );

  const onGoToMessage = useCallback(
    (ts: string) => {
      onClose();
      onNavigateToMessage?.(ts);
      messagesListMethodsRef?.current?.scrollToMessageByTs(ts);
    },
    [onClose, onNavigateToMessage, messagesListMethodsRef],
  );

  return (
    <Dialog
      isVisible={isVisible}
      onClose={onClose}
      title={t('chat.pin.pinned_messages')}>
      {pinned.map((message, index) => (
        <React.Fragment key={message.ts}>
          <PinnedRow
            message={message}
            onUnpin={handleUnpin}
            onGoToMessage={onGoToMessage}
          />
          {index < pinned.length - 1 && <Divider />}
        </React.Fragment>
      ))}
    </Dialog>
  );
}
