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 { 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';
import { emojiFromId } from '../../../utils/avatat';

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 <ListItem
                    className='relative'
                    link



                    chevron={false}
                    title={
                        <Skeleton className='w-full h-4' />
                    }

                    header={<Skeleton className='w-10 h-4' />}
                    /* after={
                       chat?.unread && chat?.unread > 0 ? (
                         <Badge>{chat?.unread}</Badge>
                       ) : undefined
                     }*/

                    text={<Skeleton className='w-full h-4' />}


                    media={

                        <div className='flex items-center h-10 w-10 bg-gray-200 dark:bg-gray-800 border-2 border-gray-200 dark:border-gray-700 rounded-full overflow-hidden justify-center text-2xl animate-pulse '>



                        </div>

                    }


                >

                </ListItem>
            })}

        </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='flex items-center h-10 w-10 bg-white dark:bg-gray-800 border-2 border-gray-200 dark:border-gray-700 rounded-full overflow-hidden justify-center text-2xl '>

                                {channel.members?.map((member) => {
                                    if (member.owner == store.userID) {
                                        return null;
                                    }
                                    return <div>
                                        {emojiFromId(member.owner ?? "")}
                                    </div>
                                })}

                            </div>

                        }

                    /*  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);
