import React from "react";
import { connect } from "react-redux";
import Slider from "react-slick";
import { getAnnouncements } from "../../../actions";

function NextArrow(props) 
{
	const { className, style, onClick } = props;

	return (
		<button 
			className={ className } 
			style={{ ...style }} 
			onClick={ onClick } 
		>
			<svg width={ 8 } height={ 12 } fill="none" xmlns="http://www.w3.org/2000/svg">
				<path
					d="m1 1 6 5-5.25 5"
					stroke="#fff"
					strokeWidth={ 2 }
					strokeLinecap="round"
					strokeLinejoin="round"
				/>
			</svg>
		</button>
	);
}

function PrevArrow(props)
{
	const { className, style, onClick } = props;

	return (
		<button 
			className={ className } 
			style={{ ...style }} 
			onClick={ onClick } 
		>
			<svg width={ 8 } height={ 12 } fill="none" xmlns="http://www.w3.org/2000/svg">
				<path
					d="M7 11 1 6l5.25-5"
					stroke="#fff"
					strokeWidth={ 2 }
					strokeLinecap="round"
					strokeLinejoin="round"
				/>
			</svg>
		</button>
	);
}

class AnnouncementsList extends React.Component 
{
	constructor(props) 
	{
		super(props);

		this.state = {
			company: {}, 
			announcements: [], 
			width: 1920
		};
	}

	componentDidMount()
	{
		this.setState({
			width: window.innerWidth
		})
		getAnnouncements().then((announcements) => this.setState({ announcements: announcements })).catch(() => {});
	}

	static getDerivedStateFromProps(nextProps, prevState) 
	{
		return {};
	}

	render() 
	{
		const settings = {
			dots: false,
			infinite: false,
			speed: 500,
			slidesToShow: this.state.width < 1279 ? 1 : 2,
			centerMode: false,
			variableWidth: this.state.width < 1279 ? true : false,
			nextArrow: <NextArrow />,
			prevArrow: <PrevArrow />
		};

		const { announcements } = this.state;

		return (
			<div className="feed">
				<div className="feed_list">
					<Slider { ...settings }>
						{ announcements !== undefined && announcements !== null && announcements.map(( announcement, index ) => (
							<div className="feed_item" key={ index }>
								<p className="item_title">{ announcement.title }</p>
								<p className="item_desc" dangerouslySetInnerHTML={{ __html: announcement.content }}></p>
								{ announcement.url !== null && (
									<a href={ announcement.url } className="item_link">Подробнее</a>
								) }
							</div>
						)) }
					</Slider>
				</div>
			</div>
		);
	}
}

function mapStateToProps(state, ownProps) 
{
	return {};
}

export default connect(mapStateToProps)(AnnouncementsList);
