'use client'
import React, {useEffect, useState} from 'react';
import {AUTH_TOKEN_KEY} from '../../constants/common';
import {getChatList, getChatMessages} from "../../actions/chat/groups";
import {useLocalStorage} from "../../hooks/useLocalStorage";
import { Link } from "../../i18n/routing";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import {message} from "antd";
import {Loader} from "../view/Loader";

dayjs.extend(relativeTime);

type CompProps = {
    locale: string;
};

export const ChatList = ({  locale }: CompProps) => {
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const [chats, setСhats] = useState<any | undefined>();
    const [loading, setLoading] = useState<boolean>(false);
    useEffect(() => {
        if (jwt) {
            setLoading(true);
            Promise.all([
                getChatList(locale, jwt),
            ])
                .then(([_groups]) => {
                   setСhats(_groups)
                })
                .catch((e) => {
                    console.log(e)
                    message.error('Не удалось загрузить данные');
                })
                .finally(() => {
                    setLoading(false);
                })
        }
    },[jwt])

    return (
        <div className="messages-session">
            <Loader isLoading={loading}>
            {chats?.directs.map((item: any, i: number) => (
                <Link
                    key={'chat'+i}
                    className="card-profile"
                    href={'messages/'+item.group.id as any}
                >
                    <div className="card-profile__header">
                        <div className="card-profile__header__portrait">
                            <img src={item.faceImageUrl} className="" alt="" />
                        </div>
                        <div className="card-profile__header__inner">
                            <div style={{ width: '100%' }}>
                                <div className="card-profile__header__name">
                                    {item.firstName}
                                    {item.newMessagesCount && (
                                        <span className="count">{item.newMessagesCount}</span>
                                    )}
                                </div>
                                <div className="card-profile__header__title">
                                    {item?.lastMessage?.text}
                                </div>
                                <div className="card-profile__header__date ">
                                    {dayjs(item?.lastMessage?.sentAt).fromNow()}
                                </div>
                            </div>
                        </div>
                    </div>
                </Link>
            ))}
            </Loader>
        </div>
    )
}