import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { InspectorControls } from '@wordpress/block-editor';
import { useEffect, useState } from "@wordpress/element";
import {
	PanelBody,
	SelectControl,
	RangeControl,
	TextControl,
	FormTokenField,
} from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ({ attributes, setAttributes, name }) => {
	const {
		selector,
		teamMembers = [],
		categories = [],
		size,
		corners,
		perRow,
		btnText,
		animationEntrance,
		animationDuration,
		animationDelay
	} = attributes;

	const [catOptions, setCatOptions] = useState([]);
	const [teamOptions, setTeamOptions] = useState([]);

	useEffect(() => {
		if (selector === 'category') {
			apiFetch({ path: '/wp/v2/team-member-categories' })
				.then((res) => {
					setCatOptions(res.map((cat) => ({ label: cat.name, value: String(cat.id) })));
				});
		}
		if (selector === 'name') {
			apiFetch({ path: '/wp/v2/team-members' })
				.then((res) => {
					setTeamOptions(res.map((post) => ({ label: post.title.rendered, value: String(post.id) })));
				});
		}
	}, [selector]);

	const mapValuesToLabels = (options, values) =>
		Array.isArray(values) ? values.map(v => {
			const found = options.find(o => o.value === v);
			return found ? found.label : v;
		}) : [];

	const mapLabelsToValues = (options, labels) =>
		labels.map(l => {
			const found = options.find(o => o.label === l);
			return found ? found.value : l;
		});

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Bio Settings', 'lead-gen')} initialOpen={true}>
					<SelectControl
						label={__('Selector', 'lead-gen')}
						value={selector}
						options={[
							{ label: __('All', 'lead-gen'), value: 'all' },
							{ label: __('Categories', 'lead-gen'), value: 'category' },
							{ label: __('Single Members', 'lead-gen'), value: 'name' },
						]}
						onChange={(val) => setAttributes({ selector: val })}
					/>

					{selector === 'category' && (
						<FormTokenField
							label={__('Choose Categories', 'lead-gen')}
							value={mapValuesToLabels(catOptions, categories)}
							suggestions={catOptions.map(o => o.label)}
							__experimentalExpandOnFocus={true}
							onChange={(tokens) => setAttributes({ categories: mapLabelsToValues(catOptions, tokens) })}
						/>
					)}

					{selector === 'name' && (
						<FormTokenField
							label={__('Choose Members', 'lead-gen')}
							value={mapValuesToLabels(teamOptions, teamMembers)}
							suggestions={teamOptions.map(o => o.label)}
							__experimentalExpandOnFocus={true}
							onChange={(tokens) => setAttributes({ teamMembers: mapLabelsToValues(teamOptions, tokens) })}
						/>
					)}

					<SelectControl
						label={__('Size', 'lead-gen')}
						value={size}
						options={[
							{ label: 'Small', value: 'sm' },
							{ label: 'Medium', value: 'md' },
							{ label: 'Large', value: 'lg' },
						]}
						onChange={(val) => setAttributes({ size: val })}
					/>

					<RangeControl
						label={__('Corner Rounding', 'lead-gen')}
						value={corners}
						onChange={(val) => setAttributes({ corners: val })}
						min={0}
						max={3}
					/>

					<RangeControl
						label={__('Cards per row', 'lead-gen')}
						value={perRow}
						onChange={(val) => setAttributes({ perRow: val })}
						min={1}
						max={12}
					/>

					<TextControl
						label={__('Button Text', 'lead-gen')}
						value={btnText}
						onChange={(val) => setAttributes({ btnText: val })}
					/>
				</PanelBody>

				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			<ServerSideRender
				block={name}
				attributes={attributes}
			/>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
