import React from 'react';
import {InspectorControls} from '@wordpress/block-editor';
import {PanelBody} from '@wordpress/components';
import {Fragment} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import {
	FloColorPicker,
	FloMultiSelectControl,
	FloRadioControl,
	FloRangeControl,
	FloSelectControl,
	FloTextControl,
	FloToggleControl,
	FloTypographySelect,
} from 'components';
const {Tip} = wp.components;
import {PostCategoriesView} from './components/CategoriesView/CategoriesViewEdit';
import {CustomCategoriesView} from './components/CustomCategoriesView/CustomCategoriesViewEdit';
import preview_image from './images/flo-category-switcher-preview.jpg';

export default function Edit(props) {
	const {attributes, setAttributes, isSelected} = props;

	const {
		activeItemColor,
		blockTitle,
		postType,
		taxonomyType,
		linksType,
		itemsGap,
		elementsColor,
		elementsColorHover,
		anyPostType,
		bordeColor,
		backgroundColor,
		allLinksLabel,
		hideHoverItem,
		indicatorColor,
		marginTop,
		marginBottom,
		mobileMarginTop,
		mobileMarginBottom,
		categoriesItems,
		itemsTypography,
		titleTypography,
		preview,
	} = attributes;

	/* Get All Post Types */
	const anyPostTypes = async () => {
		fetch(`${flo_cats_info.flo_site_url}/wp-json/floptypes/v1/flo-ptypes/`)
			.then((resp) => resp.json())
			.then((json) => setAttributes({anyPostType: json}));
	};

	/* Init anyPostTypes */
	React.useEffect(() => {
		anyPostTypes();
	}, []);

	let taxonomyListOptions = [];
	let categoryListOptions = [];

	/* Get All Taxonomies */
	const getTax = (postType) => {
		if (postType) {
			taxonomyListOptions = Object.entries(
				flo_cats_info.all_taxonomy[postType].taxonomy
			).map(([, value]) => {
				return {value: value.name, label: value.label};
			});
		}
	};

	/* Get All Categories by Taxonomy */
	if (
		postType &&
		flo_cats_info.all_taxonomy[postType].terms &&
		flo_cats_info.all_taxonomy[postType].terms[taxonomyType]
	) {
		categoryListOptions = Object.entries(
			flo_cats_info.all_taxonomy[postType].terms[taxonomyType]
		).map(([, value]) => {
			return {value: value.id, label: value.name};
		});
	}
	React.useEffect(() => {
		setAttributes({
			categoriesAllItems: categoryListOptions,
		});
	}, [postType]);
	getTax(postType);

	const [initialValuesAreSet, setInitialValuesAreSet] = React.useState(false);

	if (categoriesItems && !categoriesItems.length && !initialValuesAreSet) {
		setAttributes({
			categoriesAllItems: categoryListOptions,
		});
		// if (categoryListOptions.length > 2) {
		// 	setAttributes({
		// 		categoriesItems: [categoryListOptions[0], categoryListOptions[1]],
		// 	});
		// } else {
		//setAttributes({
		//categoriesItems: [...categoryListOptions],
		//});
		// }

		setInitialValuesAreSet(1);
	}

	if (preview) {
		return (
			<Fragment>
				<img src={fgb_blocks_info.plugin_url + 'build/' + preview_image} />
			</Fragment>
		);
	}

	return (
		<Fragment>
			<InspectorControls>
				<>
					<div
						className="enable-sticky__tip"
						style={{
							marginBottom: '24px',
							marginLeft: '10px',
							marginRight: '24px',
						}}
					>
						<Tip>
							<p>
								We do not recommend using the “Categories” Links Type for your
								Archive or for your Search Page.
							</p>
						</Tip>
					</div>
				</>
				<PanelBody title={__('Layout')} initialOpen={true}>
					<FloTextControl
						label={__('Title')}
						placeholder={__('Title')}
						value={blockTitle}
						onChange={(value) => {
							setAttributes({blockTitle: value});
						}}
					/>
					<FloRadioControl
						label={__('Links Type')}
						selected={linksType}
						options={[
							{label: 'Categories', value: 'post-cat'},
							{label: 'Custom Links', value: 'custom-links'},
						]}
						onChange={(value) => {
							setAttributes({linksType: value});
						}}
					/>
					{linksType === 'post-cat' && (
						<Fragment>
							<FloSelectControl
								label={__('Post Type')}
								value={postType}
								onChange={(value) => {
									getTax(value);
									let taxonomyType = 'post';
									if (taxonomyListOptions[0]) {
										taxonomyType = taxonomyListOptions[0].value;
									}
									setAttributes({
										categoriesItems: [],
										postType: value,
										taxonomyType,
									});
								}}
								options={anyPostType}
							/>
						</Fragment>
					)}
					{linksType === 'post-cat' && (
						<FloSelectControl
							label={__('Taxonomy')}
							value={taxonomyType}
							onChange={(value) => {
								setInitialValuesAreSet(false);
								setAttributes({categoriesItems: []});
								setAttributes({taxonomyType: value});
							}}
							options={taxonomyListOptions}
						/>
					)}
					{linksType === 'post-cat' && categoryListOptions.length > 0 && (
						<FloMultiSelectControl
							label={__('Specific Categories')}
							isMulti
							closeMenuOnSelect={false}
							value={categoriesItems}
							defaultValue={categoryListOptions}
							onChange={(value) => {
								setAttributes({categoriesItems: value});
							}}
							options={categoryListOptions}
						/>
					)}
					{linksType === 'post-cat' && (
						<FloTextControl
							label={__('All items Label')}
							value={allLinksLabel}
							onChange={(value) => {
								setAttributes({allLinksLabel: value});
							}}
						/>
					)}
					<FloToggleControl
						label={__('Display Hover Indicator')}
						checked={!!hideHoverItem}
						onChange={(value) => {
							setAttributes({hideHoverItem: value});
						}}
					/>
					<FloRangeControl
						label={__('Items Gap')}
						value={itemsGap}
						onChange={(value) => {
							setAttributes({itemsGap: value});
						}}
						min={0}
						max={100}
						unit={__('PX', 'flo')}
					/>
				</PanelBody>
				<PanelBody title={__('Typography')} initialOpen={false}>
					<FloTypographySelect
						label={__('Title Font')}
						value={titleTypography}
						onChange={(value) => setAttributes({titleTypography: value})}
					/>
					<FloTypographySelect
						label={__('Items Font')}
						value={itemsTypography}
						onChange={(value) => setAttributes({itemsTypography: value})}
					/>
				</PanelBody>
				<PanelBody title={__('Colors')} initialOpen={false}>
					<FloColorPicker
						title={__('Items Color Default')}
						value={elementsColor}
						onChange={(value) => setAttributes({elementsColor: value})}
					/>
					<FloColorPicker
						title={__('Items Color Hover')}
						value={elementsColorHover}
						onChange={(value) => setAttributes({elementsColorHover: value})}
					/>
					<FloColorPicker
						title={__('Indicator Color')}
						value={indicatorColor}
						onChange={(value) => setAttributes({indicatorColor: value})}
					/>
					<FloColorPicker
						title={__('Active Category Color')}
						value={activeItemColor || '#000'}
						onChange={(value) => setAttributes({activeItemColor: value})}
					/>
					<FloColorPicker
						title={__('Line Color')}
						value={bordeColor}
						onChange={(value) => setAttributes({bordeColor: value})}
					/>
					<FloColorPicker
						title={__('Background Color')}
						value={backgroundColor}
						onChange={(value) => setAttributes({backgroundColor: value})}
					/>
				</PanelBody>
				<PanelBody title={__('Margins')} initialOpen={false}>
					<p>{__('Desktop')}</p>
					<FloRangeControl
						label={__('Margin Top')}
						value={marginTop}
						onChange={(value) => {
							setAttributes({marginTop: value});
						}}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
					<FloRangeControl
						label={__('Margin Bottom')}
						value={marginBottom}
						onChange={(value) => {
							setAttributes({marginBottom: value});
						}}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
					<p>{__('Mobile')}</p>
					<FloRangeControl
						label={__('Top Margin')}
						value={mobileMarginTop}
						onChange={(val) => setAttributes({mobileMarginTop: val})}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
					<FloRangeControl
						label={__('Bottom Margin')}
						value={mobileMarginBottom}
						onChange={(val) => setAttributes({mobileMarginBottom: val})}
						min={-100}
						max={100}
						unit={__('PX', 'flo')}
					/>
				</PanelBody>
			</InspectorControls>
			<PostCategoriesView {...props} categoriesItems={categoriesItems} />
			{linksType === 'custom-links' && isSelected && (
				<CustomCategoriesView {...props} />
			)}
		</Fragment>
	);
}
