import {useMemo} from 'react';
import {Icon} from '@tabler/icons-react-native';
import {formatSecondsToTime} from '@modules/chat/utils';
import {AudioAsset, Message, VideoAsset} from '@modules/chats/interfaces';
import {usePrefixIconAndText} from '@modules/chats/hooks/usePrefixIconAndText';
import {
  getChatImage,
  isAudioAsset,
  isPictureAsset,
  isVideoAsset,
} from '@modules/chats/utils';
import {mapAssetToUrl} from '@modules/chats/utils/mappers/assetMapper';
import {IMAGE_SIZE_TINY_PX} from '@modules/chats/constants';

interface Params {
  message: Message | undefined;
}

export interface PinnedMessageDisplayResult {
  displayText: string;
  PrefixIcon: Icon | null;
  thumbnailUrl: string | undefined;
}

export const usePinnedMessageDisplay = ({
  message,
}: Params): PinnedMessageDisplayResult => {
  const assets = message?.attachments?.length ? message.attachments : undefined;

  // Pinned previews are tiny rows — request the TINY variant and rely on
  // ExpoImage's disk cache (already warmed by the chat tile that opened
  // this thread). No FileHandler involvement.
  const thumbnailUrl = useMemo(() => {
    if (!assets || assets.length !== 1) return undefined;
    const asset = assets[0];
    if (isVideoAsset(asset)) {
      const remote = (asset as VideoAsset).thumbnail_url;
      return remote
        ? getChatImage.addSize(remote, IMAGE_SIZE_TINY_PX)
        : undefined;
    }
    if (isPictureAsset(asset)) {
      const remote = mapAssetToUrl(asset);
      return remote
        ? getChatImage.addSize(remote, IMAGE_SIZE_TINY_PX)
        : undefined;
    }
    return undefined;
  }, [assets]);

  const {PrefixIcon, defaultText} = usePrefixIconAndText({assets});

  const displayText = useMemo(() => {
    const text = message?.formatted_text || message?.text || defaultText;
    if (assets?.length === 1 && isAudioAsset(assets[0])) {
      const durationMs = (assets[0] as AudioAsset).audio_duration_ms ?? 0;
      const formatted = formatSecondsToTime(Math.round(durationMs / 1000));
      return `${text} (${formatted})`;
    }
    return text;
  }, [message?.formatted_text, message?.text, defaultText, assets]);

  return {
    displayText,
    PrefixIcon,
    thumbnailUrl,
  };
};
