import 'dayjs/locale/ru';

import { BsTrash3 } from 'react-icons/bs';

import { ShmChannelMessageType } from '../../../api/types';
import { usePresentation } from '../../../presentation/PresentationContext';
import store from '../../../stores/store';
import { authorColor } from '../../../utils/authorColor';
import { emojiFromId } from '../../../utils/avatat';
import FileTypeIcon from './FileTypeIcon';

const MessageReplayItem = ({
  msg,
  onClick,
  variant = 'inline',
}: {
  msg: ShmChannelMessageType;
  onClick: () => void;
  variant?: 'inline' | 'compose';
}) => {
  const { id: presentationId } = usePresentation();
  const isIg = presentationId === 'instagram';

  const isDeleted = !!msg.deleted;
  const preview = isDeleted
    ? null
    : msg.text ||
      (msg.voice?.url
        ? '🎙 Голосовое сообщение'
        : msg.attachments?.[0]?.name || '📎 Файл');

  const ownerId = msg.owner ?? '';
  const isOwn = ownerId && ownerId === store.userID;
  const color = authorColor(ownerId);
  const title = isOwn ? 'Вы' : emojiFromId(ownerId) + ' Собеседник';

  const round = isIg ? 'rounded-2xl' : 'rounded-md';
  const surface =
    variant === 'compose'
      ? isIg
        ? 'bg-[var(--tg-bg-secondary)]/80 backdrop-blur-md mx-1 border border-[var(--tg-divider)]/70'
        : 'bg-[var(--tg-bg-secondary)] mx-1'
      : isIg
        ? 'bg-[var(--tg-bg)]/55 backdrop-blur-[2px] border border-[var(--tg-divider)]/55'
        : 'bg-black/5 dark:bg-white/5';

  return (
    <div
      onClick={(e) => {
        e.stopPropagation();
        onClick();
      }}
      id={`replay-msg-${msg._id}`}
      className={`cursor-pointer active:opacity-70 relative pl-3 py-1.5 my-1.5
        ${round} overflow-hidden ${surface}`}
    >
      <div
        className={
          isIg
            ? 'absolute left-0 top-2 bottom-2 w-[3px] rounded-full bg-gradient-to-b from-[#f58529] via-[#dd2a7b] to-[#8134af]'
            : 'absolute left-0 top-1 bottom-1 w-[3px] rounded-full'
        }
        style={isIg ? undefined : { background: color }}
      />
      <div
        className="text-[13px] font-semibold truncate leading-4"
        style={{ color }}
      >
        {title}
      </div>
      {isDeleted ? (
        <div className="text-[13px] opacity-70 flex items-center gap-1.5">
          <BsTrash3 className="w-3.5 h-3.5" /> Сообщение удалено
        </div>
      ) : (
        <div className="flex items-center gap-1.5 text-[13px] opacity-90 truncate">
          {msg.attachments?.[0] && (
            <div className="shrink-0 w-3.5 h-3.5">
              <FileTypeIcon size={14} doc={msg.attachments[0]} />
            </div>
          )}
          <span className="truncate">{preview}</span>
        </div>
      )}
    </div>
  );
};

export default MessageReplayItem;
