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 { 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';
  /** Десктоп: пока грузится выбранный чат — блокируем клики по остальным строкам. */
  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={
        id === 'whatsapp'
          ? 'flex flex-col gap-0'
          : id === 'instagram'
            ? 'flex flex-col gap-2 px-2 py-2 bg-[var(--tg-bg-secondary)] min-h-0'
            : 'flex flex-col gap-0.5 px-1 py-1'
      }
    >
      {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);
