// Import Post Components
import Blog from './blog';

import {Component, Fragment} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import {
	RadioImageControl,
	FloRangeControl,
	FloToggleControl,
	FloRichText,
	FloTagControl,
	FloTypographySelect,
	FloColorPicker,
} from 'components';
import {PanelBody, Spinner} from '@wordpress/components';
import {InspectorControls} from '@wordpress/block-editor';

import {withSelect} from '@wordpress/data';

import {
	LoadGoogleFonts,
	getStyleForTypography,
} from 'components/typography-select/utils';
import {getColorByValue} from 'components/color-picker/utils';

import preview_image from './images/flo-related-items-preview.jpg';

class FBGPostGrid extends Component {
	constructor() {
		super(...arguments);
	}

	componentDidMount() {}

	render() {
		// Caching all Props.
		const {
			attributes,
			setAttributes,
			latestPosts,
			categoriesList,
			taxonomyList,
		} = this.props;

		// Caching all attributes.
		const {
			relatedTitle,
			relatedTitleTypography,
			titleTagName,
			relatedTitleColor,
			gapBetweenItems,
			masonry,
			imageHeight,

			postTitleFont,
			titleColor,
			metaColor,
			displayPostDate,
			postDateFont,
			displayPostTaxonomy,
			postTaxonomyFont,
			relatedBackgroundColor,
			topMargin,
			bottomMargin,
			mobileTopMargin,
			mobileBottomMargin,
			preview,
		} = attributes;

		let taxonomyListOptions = [{value: '', label: __('Select Taxonomy')}];

		let categoryListOptions = [{value: '', label: __('All')}];

		if ('' !== taxonomyList) {
			Object.keys(taxonomyList).map((item) => {
				return taxonomyListOptions.push({
					value: taxonomyList[item]['name'],
					label: taxonomyList[item]['label'],
				});
			});
		}

		if ('' !== categoriesList) {
			Object.keys(categoriesList).map((item) => {
				return categoryListOptions.push({
					value: categoriesList[item]['id'],
					label: categoriesList[item]['name'],
				});
			});
		}

		// All Controls.
		const inspectorControls = (
			<InspectorControls>
				<PanelBody title={__('Layout')}>
					<RadioImageControl
						label="Featured Image Type"
						classNameProp="flo-related-type"
						options={[
							{
								value: false,
								label: 'Fixed',
								preview: `${fgb_blocks_info.plugin_root}images/flo-block-related-items-image-fixed.jpg`,
							},
							{
								value: true,
								label: 'Original',
								preview: `${fgb_blocks_info.plugin_root}images/flo-block-related-items-image-original.jpg`,
							},
						]}
						selected={masonry}
						onChange={() => {
							setAttributes({
								masonry: !masonry,
							});
						}}
					/>
					{!masonry && (
						<FloRangeControl
							label={__('Image Height', 'flo')}
							value={imageHeight}
							onChange={(val) => setAttributes({imageHeight: val})}
							min={100}
							max={1000}
							className="related-image-height"
							unit={__('PX', 'flo')}
						/>
					)}
					<FloRangeControl
						label={__('Gap Between Items', 'flo')}
						value={gapBetweenItems}
						onChange={(val) => setAttributes({gapBetweenItems: val})}
						min={0}
						max={300}
						unit={__('PX', 'flo')}
					/>

					<FloToggleControl
						label={__('Show Item Date', 'flo')}
						checked={displayPostDate}
						onChange={() => setAttributes({displayPostDate: !displayPostDate})}
					/>
					<FloToggleControl
						label={__('Show Taxonomy', 'flo')}
						checked={displayPostTaxonomy}
						onChange={() =>
							setAttributes({displayPostTaxonomy: !displayPostTaxonomy})
						}
					/>
				</PanelBody>

				<PanelBody title={__('Typography')} initialOpen={false}>
					<FloTypographySelect
						label={__('Block Title Font')}
						value={relatedTitleTypography}
						onChange={(value) => setAttributes({relatedTitleTypography: value})}
					/>
					<FloTypographySelect
						label={__('Title Font')}
						value={postTitleFont}
						onChange={(value) => setAttributes({postTitleFont: value})}
					/>
					<FloTagControl
						label={__('Title HTML Tag')}
						tagName={titleTagName}
						onClick={(value) => {
							setAttributes({titleTagName: value});
						}}
					/>

					{displayPostDate && (
						<FloTypographySelect
							label={__('Data Font')}
							value={postDateFont}
							onChange={(value) => setAttributes({postDateFont: value})}
						/>
					)}

					{displayPostTaxonomy && (
						<FloTypographySelect
							label={__('Taxonomy Font')}
							value={postTaxonomyFont}
							onChange={(value) => setAttributes({postTaxonomyFont: value})}
						/>
					)}
				</PanelBody>

				<PanelBody title={__('Colors')} initialOpen={false}>
					<FloColorPicker
						title={__('Block Background Color')}
						value={relatedBackgroundColor}
						onChange={(value) => setAttributes({relatedBackgroundColor: value})}
					/>
					<FloColorPicker
						title={__('Block Title Color')}
						value={relatedTitleColor}
						onChange={(value) => setAttributes({relatedTitleColor: value})}
					/>

					<FloColorPicker
						title={__('Item Title Color')}
						value={titleColor}
						onChange={(value) => setAttributes({titleColor: value})}
					/>

					{(displayPostDate || displayPostTaxonomy) && (
						<FloColorPicker
							title={__('Category & Date Color')}
							value={metaColor}
							onChange={(value) => setAttributes({metaColor: value})}
						/>
					)}
				</PanelBody>
				<PanelBody title={__('Margins')} initialOpen={false}>
					<p>{__('Desktop')}</p>
					<FloRangeControl
						label={__('Top', 'flo')}
						value={topMargin}
						onChange={(val) => setAttributes({topMargin: val})}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
					<FloRangeControl
						label={__('Bottom', 'flo')}
						value={bottomMargin}
						onChange={(val) => setAttributes({bottomMargin: val})}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
					<p>{__('Mobile')}</p>
					<FloRangeControl
						label={__('Top', 'flo')}
						value={mobileTopMargin}
						onChange={(val) => setAttributes({mobileTopMargin: val})}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
					<FloRangeControl
						label={__('Bottom', 'flo')}
						value={mobileBottomMargin}
						onChange={(val) => setAttributes({mobileBottomMargin: val})}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
				</PanelBody>
			</InspectorControls>
		);

		const hasPosts = Array.isArray(latestPosts) && latestPosts.length;

		if (!hasPosts) {
			return (
				<Fragment>
					{inspectorControls}

					{!Array.isArray(latestPosts) ? <Spinner /> : __('No post found!')}
				</Fragment>
			);
		}
		if (preview) {
			return (
				<Fragment>
					<img src={fgb_blocks_info.plugin_url + '/build/' + preview_image} />
				</Fragment>
			);
		}
		return (
			<Fragment>
				{inspectorControls}
				<>
					<div
						className="flo-block-related-grid-block alignfull"
						style={{
							'--top-margin': topMargin + 'px',
							'--bottom-margin': bottomMargin + 'px',
							'--mobile-top-margin': mobileTopMargin + 'px',
							'--mobile-bottom-margin': mobileBottomMargin + 'px',
							'--block-background-color': getColorByValue(
								relatedBackgroundColor
							),
						}}
					>
						<LoadGoogleFonts typographies={[relatedTitleTypography]} />
						<div
							data-font={
								relatedTitleTypography.type === 'theme'
									? relatedTitleTypography.theme
									: ''
							}
							style={getStyleForTypography(
								'related-title',
								relatedTitleTypography
							)}
						>
							<FloRichText
								tagName={titleTagName} // The tag here is the element output and editable in the admin
								className="flo-block-related-title"
								value={relatedTitle} // Any existing content, either from the database or an attribute default
								onChange={(val) => setAttributes({relatedTitle: val})} // Store updated content as a block attribute
								placeholder={__('RELATED POSTS')} // Display this text before any content has been added by the user
								style={{
									'--related-title-color': getColorByValue(relatedTitleColor),
								}}
							/>
						</div>

						<Blog
							attributes={attributes}
							className={this.props.className}
							latestPosts={latestPosts}
							block_id={this.props.clientId.substr(0, 8)}
							categoriesList={categoriesList}
						/>
					</div>
				</>
			</Fragment>
		);
	}
}

export default withSelect((select, props) => {
	const {categories, postsToShow, postType, taxonomyType} = props.attributes;

	let allTaxonomy = fgb_blocks_info.all_taxonomy;
	let currentTax = allTaxonomy[postType];
	let categoriesList = [];
	let rest_base = '';

	if ('undefined' !== typeof currentTax) {
		if ('undefined' !== typeof currentTax['taxonomy'][taxonomyType]) {
			rest_base =
				currentTax['taxonomy'][taxonomyType]['rest_base'] === false ||
				currentTax['taxonomy'][taxonomyType]['rest_base'] === null
					? currentTax['taxonomy'][taxonomyType]['name']
					: currentTax['taxonomy'][taxonomyType]['rest_base'];
		}

		if ('' !== taxonomyType) {
			if (
				'undefined' !== typeof currentTax['terms'] &&
				'undefined' !== typeof currentTax['terms'][taxonomyType]
			) {
				categoriesList = currentTax['terms'][taxonomyType];
			}
		}
	}

	let latestPostsQuery = {
		per_page: postsToShow,
	};

	latestPostsQuery[rest_base] = categories;

	/**
	 * If we are on back end we use json file with placeholder data:
	 */

	/*return {
		latestPosts: getEntityRecords('postType', postType, latestPostsQuery),
		categoriesList: categoriesList,
		taxonomyList:
			'undefined' !==typeof currentTax ? currentTax['taxonomy'] : [],
	};*/

	return {
		latestPosts: require('./utils/placeholder-related-items.json'),
		categoriesList: categoriesList,
		taxonomyList:
			'undefined' !== typeof currentTax ? currentTax['taxonomy'] : [],
	};
})(FBGPostGrid);
