import React, {Component} from 'react'
import axios from 'axios'
import _map from 'lodash/map'
import Card from './Card'
import LazyLoad from 'react-lazyload';
import './CardList.css'

import 'reactjs-popup/dist/index.css';

const customStyles = {
    content: {
        top: '50%',
        left: '50%',
        right: 'auto',
        bottom: 'auto',
        marginRight: '-50%',
        transform: 'translate(-50%, -50%)',
    }
};

type CardListProps = {
    filter: String
}

type CardListState = {
    data: any;
    modelIsOpen: boolean
}

export default class CardList extends Component<CardListProps, CardListState> {

    constructor(props: CardListProps) {
        super(props);
        this.state = {
            data: [],
            modelIsOpen: false
        }
    }

    getToken() {
        const tokenString = localStorage.getItem('token');
        // @ts-ignore
        const userToken = JSON.parse(tokenString);
        return userToken?.token
    };

    getData() {
        axios.get(`${process.env.REACT_APP_API_URL}/card`, {
            headers: {
                'Authorization': `Bearer ${this.getToken()}`
            }
        }).then(res => {
            let data = res.data
            this.setState({data: data})
        })
    }

    componentDidMount() {
        this.getData()
    }

    render() {
        // @ts-ignore
        const {data} = this.state
        return (
            <div className={"card-container"}>
                {_map(data, d => (
                    (this.props.filter === 'all' || d.color === this.props.filter) &&
                    <div>
                        <LazyLoad scroll={true}>
                            <Card
                                title={`${d.color} ${d.name}`}
                                info={d.info}
                                special={d.special}
                                value={d.value}
                                count={d.count}
                                isFlipped={false}
                                back={`${process.env.REACT_APP_API_URL}/card/${d._id}/back`}
                                front={`${process.env.REACT_APP_API_URL}/card/${d._id}/front`}
                            />
                        </LazyLoad>
                    </div>
                ))}
            </div>
        )
    }
}
