import { url } from '../../App';

import * as React from 'react';
import { useSelector } from "react-redux"
import { useHistory } from 'react-router-dom';

import { CardHeader, Avatar, Typography, Button, Box } from '@mui/material';

import './style.scss'


// Компонент карточки-рекомендации юзера 
export function RecommendedCard({ data }) {
    const history = useHistory()

    // проверка, является ли пользователь моим подписчиком
    const myFollowings = useSelector(state => state?.promise?.AboutMe?.payload?.following)
    const isFollowing = myFollowings && myFollowings.some(item => item._id === data._id)

    // переход на аккаунт
    function toAccount() {
        history.push(`user/${data._id}`)
    }

    return (
        <CardHeader
            avatar={
                <Avatar
                    src={url + data?.avatar?.url}
                    aria-label="recipe"
                    sx={{ width: 36, height: 36 }}
                />
            }

            action={
                <Button
                    variant="text"
                    size="small"
                    onClick={() => console.log('click')}
                >
                    {isFollowing ? 'Отписаться' : 'Подписаться'}
                </Button>
            }

            title={
                <Typography
                    sx={{
                        cursor: 'pointer',
                        width: 'fit-content'
                    }}
                    variant="subtitle2"
                    color='text.secondary'
                    onClick={toAccount}
                >
                    {data?.login || 'anon user'}
                </Typography>
            }
        />
    )
}


function Recommended() {

    const followers = useSelector(state => state?.promise?.FindFollowers?.payload)
    const followings = useSelector(state => state?.promise?.FindFollowings?.payload)
    const myFollowings = useSelector(state => state?.promise?.AboutMe?.payload?.following)

    let recommendedList = []

    if (followers && followings && myFollowings) {
        const joinArr = [
            ...followers,
            ...followings.filter((item) =>
                !followers.some((current) => current._id === item._id)
            )
        ].filter((item) =>
            !myFollowings.some((current) => current._id === item._id)
        )

        const random = 10
        // теперь оставляем в массиве только random рандомных элементов элементов
        for (let i = 0; i < random; i++) {
            const randomIndex = Math.floor(Math.random() * joinArr.length)
            recommendedList.push(joinArr[randomIndex])

            // удаляем элементы из массива, чтобы снова их не показывать
            joinArr.splice(randomIndex, 1)
        }
    }


    return (
        <Box sx={{
            marginTop: '10px'
        }}>
            <Box sx={{
                padding: '0 24px'
            }}>
                <Typography
                    variant="subtitle1"
                    color='text.secondary'
                    gutterBottom
                >
                    Рекомендации для Вас
                </Typography>
            </Box>

            <Box
                className='recommendedBox'

                sx={{
                    margin: '8px 0',
                    width: '95%',
                    paddingLeft: '8px',
                    height: '300px',
                    overflowY: 'auto'
                }}>
                {recommendedList && recommendedList.map(item => <RecommendedCard key={item._id} data={item} />)}
            </Box>
        </Box>
    )
}


export default Recommended