import 'dayjs/locale/ru';

import { useEffect } from 'react';

import dayjs from 'dayjs';
import { observer } from 'mobx-react';

import { ExtensionsStore } from '../../../api/request';
import {
  ShmChannelMessageType,
  ShmChannelType,
} from '../../../api/types';
import { dialogsListChromeClass } from '../../../presentation/dialogsListChrome';
import { usePresentation } from '../../../presentation/PresentationContext';
import store from '../../../stores/store';

dayjs.locale('ru');

const lastMessageText = (message?: ShmChannelMessageType | null) => {
  if (!message) return '';
  if (message.deleted) return 'Сообщение удалено';
  if (message.text) return message.text;
  if (message.attachments?.length) return '📎 Файл';
  if (message.voice?.url) return '🎙 Голосовое сообщение';
  return '';
};

const formatDialogTime = (ts?: number) => {
  if (!ts) return '';
  const d = dayjs.unix(ts);
  const now = dayjs();
  if (d.isSame(now, 'day')) return d.format('HH:mm');
  if (d.isSame(now.subtract(1, 'day'), 'day')) return 'вчера';
  if (d.isSame(now, 'year')) return d.format('D MMM');
  return d.format('DD.MM.YY');
};

const DialogsList = ({
  selectChannelID,
  channelTab,
  desktopChannelSwitchBlocked = false,
  onSelectChannel,
}: {
  selectChannelID: string | null;
  channelTab?: 'member' | 'join' | 'closed';
  /** Десктоп: пока грузится выбранный чат — блокируем клики по остальным строкам. */
  desktopChannelSwitchBlocked?: boolean;
  onSelectChannel: (channel: ShmChannelType) => void;
  selectChannel: ShmChannelType | null;
}) => {
  const {
    id,
    components: {
      DialogRow,
      DialogsListSkeleton,
      EmptyDialogs,
    },
  } = usePresentation();

  useEffect(() => {
    store.loadChannelList();
    store.startChannelListPolling();
    return () => store.stopChannelListPolling();
  }, [channelTab]);

  if (store.dialogsLoading) return <DialogsListSkeleton />;

  if (!store.channelList.length) return <EmptyDialogs />;

  return (
    <div className={dialogsListChromeClass[id]}>
      {store.channelList.map((channel) => {
        const lastMessage = ExtensionsStore.shmChannelMessagesByID(
          channel.lastMessage
        );
        const unread = channel.unreadCounts?.[store.userID as any] ?? 0;
        const closed = !!channel.closed;
        const otherMember = channel.members?.find((m) => m.owner != store.userID);
        const isOwn = lastMessage?.owner == store.userID;
        const preview = closed ? 'Диалог закрыт' : lastMessageText(lastMessage);
        const showReadCheck = !!(isOwn && lastMessage?.viewed);

        return (
          <DialogRow
            key={channel._id}
            avatarId={otherMember?.owner ?? channel._id ?? ''}
            title={channel.name || 'Без имени'}
            preview={preview}
            timeLabel={formatDialogTime(
              lastMessage?.created_at ?? channel.created_at
            )}
            selected={!store.isMobile() && selectChannelID === channel._id}
            closed={closed}
            switchBlocked={
              desktopChannelSwitchBlocked && selectChannelID !== channel._id
            }
            onClick={() => channel._id && onSelectChannel(channel)}
            showReadCheck={showReadCheck}
            unread={unread}
          />
        );
      })}
    </div>
  );
};

export default observer(DialogsList);
