import 'dayjs/locale/ru'; // load on demand

import React, { useEffect } from 'react';

import dayjs from 'dayjs';
import {
  Badge,
  List,
  ListItem,
} from 'konsta/react';
import { observer } from 'mobx-react';
import {
  BiMessageSquareDetail,
  BiMessageSquareX,
} from 'react-icons/bi';
import { LuMessageSquare } from 'react-icons/lu';

import { ExtensionsStore } from '../../../api/request';
import {
  ShmChannelMessageType,
  ShmChannelType,
} from '../../../api/types';
import Skeleton from '../../../components/Skeleton';
import store from '../../../stores/store';

dayjs.locale("ru");


const LastMessageText = ({ message }: { message?: ShmChannelMessageType | null }) => {


    if (!!message?.deleted) {
        return "Удалено";
    }

    if (!message) {
        return "...";
    }

    if (message?.text) {
        return message?.text;
    }

    if (!!message.attachments?.length) {
        return "Прикрепленные файлы";
    }

    if (message?.voice?.url) {
        return "Аудио сообщение";
    }

    return "...";
};


const DialogsList = ({ selectChannelID, channelTab, onSelectChannel }: { selectChannelID: string | null; channelTab?: "member" | "join"; onSelectChannel: (channel: ShmChannelType) => void; selectChannel: ShmChannelType | null }) => {

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


    return (<List strong outline>
        {store.dialogsLoading ? <div>


            {[1, 2, 3, 4].map(() => {
                return <Skeleton className='h-20 mb-2' />
            })}

        </div> :

            !store.channelList.length ? <div className='py-10 opacity-50'>

                <div className='flex flex-col items-center justify-center h-full'>
                    <LuMessageSquare
                        size={24}
                    />
                    <div className='text-sm mt-2'>Нет диалогов</div>
                </div>
            </div> : store.channelList.map((channel) => {

                const lastMessage = ExtensionsStore.shmChannelMessagesByID(channel.lastMessage);

                const unreadCount = channel.unreadCounts?.[store.userID as any] ?? 0

                return (<>
                    <ListItem
                        className='relative'
                        style={{
                            opacity: !!channel.closed ? 0.5 : 1,

                        }}
                        after={!!unreadCount ? <Badge>{unreadCount}</Badge> : undefined}
                        link


                        onClick={() => {
                            if (channel._id) {
                                onSelectChannel(channel);
                            }
                        }}
                        chevron={false}
                        title={
                            !!channel.name ? channel.name : "Без имени"
                        }

                        header={!!channel.closed ? "Диалог закрыт" : undefined}
                        /* after={
                           chat?.unread && chat?.unread > 0 ? (
                             <Badge>{chat?.unread}</Badge>
                           ) : undefined
                         }*/

                        text={<LastMessageText message={lastMessage} />}

                        footer={!!channel.created_at ? dayjs.unix(channel.created_at).format("DD.MM.YYYY HH:mm") : ""}
                        media={
                            <div className='w-10 h-10 flex items-center justify-center text-2xl text-gray-500 bg-gray-100 rounded-full'>
                                {!!channel.closed ? <BiMessageSquareX /> : <BiMessageSquareDetail />}
                            </div>
                        }
                    >
                        {!store.isMobile() && selectChannelID === channel._id && (
                            <div
                                className='absolute top-0 left-0 w-full h-full pointer-events-none'
                                style={{
                                    backgroundColor: 'var(--k-color-primary)',
                                    opacity: 0.1,
                                }}
                            />
                        )}
                    </ListItem>
                </>
                );
            })}
    </List>


    );
};

export default observer(DialogsList);
