import { __ } from '@wordpress/i18n';
import { PanelBody, RangeControl, TextareaControl } from '@wordpress/components';
import { useBlockProps, InspectorControls, RichText, PanelColorSettings } from '@wordpress/block-editor';
import axios from 'axios';
import { useState, useEffect } from '@wordpress/element';
const Edit = ({ attributes, setAttributes }) => {
	const { title, items, backgroundColor, textColor, titleTextColor, numberOfItems, rssURL } = attributes;

	const fetchDataFromRSS = async () => {
		try {
			const response = await axios.get(`https://api.rss2json.com/v1/api.json?rss_url=${rssURL}`);
			if (response.data && response.data.items) {
				const items = response.data.items;
				setAttributes({ items });
			} else {
				console.error('Empty or invalid response from the RSS feed.');
				setAttributes({ items: [] });
			}
		} catch (error) {
			console.error('Error fetching data from the RSS feed:', error);
			setAttributes({ items: [] });
		}
	};

	const onChangeTitle = (value) => {
		setAttributes({ title: value });
	};

	useEffect(() => {
		fetchDataFromRSS();
	}, [rssURL]);

	const onChangeBackgroundColor = (newBgColor) => {
		setAttributes({ backgroundColor: newBgColor });
	};

	const onChangeTextColor = (newTextColor) => {
		setAttributes({ textColor: newTextColor });
	};
	const onChangeTitleTextColor = (newTextColor) => {
		setAttributes({ titleTextColor: newTextColor });
	};
	const onChangeRssUrl = (newRssUrl) => {
		setAttributes({ rssURL: newRssUrl });
	}
	const onChangeNumberOfItems = (newNumberOfItems) => {
		setAttributes({ numberOfItems: newNumberOfItems });
	};
	return (
		<div {...useBlockProps()}>
			<InspectorControls>
				<PanelBody title={__('RSS Feed Settings', 'artcloud-blocks')}>
					<TextareaControl
						label={__('Add RSS Feed URL', 'artcloud-blocks')}
						help={__('Add RSS Feed URL to fetch rss feeds', 'artcloud-blocks')}
						value={rssURL}
						onChange={onChangeRssUrl}
					/>
					<RangeControl
						label={__('Number of Items', 'artcloud-blocks')}
						value={numberOfItems}
						onChange={onChangeNumberOfItems}
						min={3}
						max={items ? items.length : 1}
					/>
				</PanelBody>
				<PanelColorSettings
					title={__('Color Settings', 'artcloud-blocks')}
					icon="admin-appearance"
					initialOpen
					colorSettings={[
						{
							value: backgroundColor,
							onChange: onChangeBackgroundColor,
							label: __('Background Color', 'artcloud-blocks')
						},
						{
							value: titleTextColor,
							onChange: onChangeTitleTextColor,
							label: __('Title Text Color', 'artcloud-blocks')
						},
						{
							value: textColor,
							onChange: onChangeTextColor,
							label: __('Text Color', 'artcloud-blocks')
						},
					]}
				></PanelColorSettings>
			</InspectorControls>
			<RichText
				tagName="h1"
				style={{ color: titleTextColor }}
				className="rss-block-title"
				placeholder={__('Enter title', 'artcloud-blocks')}
				value={title}
				onChange={onChangeTitle}
				allowedFormats={[]}
			/>
			{items && items.length > 0 ? (
				<div className='row'>
					{items.slice(0, numberOfItems).map((item, index) => (
						<div className='artcloud-item col-4' style={{ backgroundColor: backgroundColor }}>
							<div className="artcloud-rssImg">
								<img src={item.enclosure.link} alt="" width={300} />
							</div>
							<div className="artcloud-content">
								<h6 style={{ color: textColor }}>
									{new Date(new Date(item.pubDate).getTime() + 2 * 60 * 60 * 1000).toLocaleDateString('fi-FI', {
										year: 'numeric',
										month: '2-digit',
										day: '2-digit',
										hour: '2-digit',
										minute: '2-digit',
										second: '2-digit',
										hour12: false,
									})} EET
								</h6>
								<a href={item.link}>
									<h3 style={{ color: textColor }}>{item.title.slice(0, 80)}</h3>
								</a>
								<p style={{ color: textColor }}>{item.description.slice(0, 170) + '...'}</p>
							</div>
						</div>
					))}
				</div>
			) : (
				<p>{__('Please Add/Check the RSS URL', 'artcloud-blocks')}</p>
			)}
		</div>
	);
};

export default Edit;
