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

import React, {
  useEffect,
  useState,
} 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,
  rpc,
} 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 = ({ channelTab, onSelectChannel, selectChannelID }: { selectChannelID: string | null, channelTab?: "member" | "join", onSelectChannel: (channel: ShmChannelType) => void, selectChannel: ShmChannelType | null }) => {


    const [loading, setLoading] = useState(false);

    const [channelList, setChannelList] = useState<ShmChannelType[]>([]);

    useEffect(() => {

        setLoading(true);
        if (!channelTab || channelTab === "member") {
            rpc.channelList({}, ["shmChannelMessages"]).then(({ result: data }) => {
                setChannelList(data?.data ?? []);
            }).finally(() => {
                setLoading(false);
            });
        } else {

            rpc.joinChannelList({}, ["shmChannelMessages"]).then(({ result: data }) => {
                setChannelList(data?.data ?? []);
            }).finally(() => {
                setLoading(false);
            });
        }


    }, [channelTab]);


    //  const channelList = channelTab === "join" ? store.joinChannelList : store.channelList;


    return (<List strong outline>
        {loading ? <div>


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

        </div> :

            !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> : channelList.map((channel) => {

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

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

                return (
                    <ListItem
                        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(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>
                        }
                    />
                );
            })}
    </List>


    );
};

export default observer(DialogsList);
