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

const Edit = ({ attributes, setAttributes, name }) => {
	const {
		displayType,
		sliderControls,
		sliderPageSize,
		maxReviews,
		selector,
		categories = [],
		testimonials = [],
		orderBy,
		order,
		animationEntrance,
		animationDuration,
		animationDelay
	} = attributes;

	const [catOptions, setCatOptions] = useState([]);
	const [testimonialOptions, setTestimonialOptions] = useState([]);
	const wrapperRef = useRef(null);

	useEffect(() => {
		if (displayType !== 'slider') return;
		if (!wrapperRef.current) return;

		const observer = new MutationObserver(() => {
			const slider = wrapperRef.current.querySelector('.testimonial__slider');
			if (slider && !slider.dataset.initialized) {
				initSwiper(slider, { allowTouchMove: false });
				slider.dataset.initialized = '1';
			}
		});

		observer.observe(wrapperRef.current, {
			childList: true,
			subtree: true,
		});

		return () => observer.disconnect();
	}, [displayType]);

	useEffect(() => {
		if (selector === 'categories') {
			apiFetch({ path: '/wp/v2/testimonial-categories' })
				.then((res) => {
					setCatOptions(res.map((cat) => ({ label: cat.name, value: String(cat.id) })));
				})
				.catch((err) => console.error('Failed to load categories:', err));
		} else if (selector === 'name') {
			if (selector === 'name') {
				apiFetch({ path: '/wp/v2/testimonials' })
					.then((res) => {
						setTestimonialOptions(res.map((post) => ({ label: post.title.rendered, value: String(post.id) })));
					})
					.catch((err) => console.error('Failed to load testimonials:', err));
			}
		}
	}, [selector]);

	const mapValuesToLabels = (options, values) =>
		Array.isArray(values) && values.length
			? options.reduce((acc, opt) => {
				if (values.includes(opt.value)) {
					acc.push(opt.label);
				}
				return acc;
			}, [])
			: [];

	const mapLabelsToValues = (options, labels) =>
		options.reduce((acc, opt) => {
			if (labels.includes(opt.label)) acc.push(opt.value);
			return acc;
		}, []);

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__testimonials ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Testimonials Settings', 'lead-gen')} initialOpen={true}>
					<SelectControl
						label={__('Display Type', 'lead-gen')}
						value={displayType}
						options={[
							{ label: __('Card', 'lead-gen'), value: 'card' },
							{ label: __('Slider', 'lead-gen'), value: 'slider' },
							{ label: __('Block Quote', 'lead-gen'), value: 'quote' },

						]}
						onChange={(val) => setAttributes({ displayType: val })}
					/>

					{'slider' === displayType && (
						<>
							<ToggleControl
								label={__('Slider Controls', 'lead-gen')}
								checked={!!sliderControls}
								onChange={(val) => setAttributes({ sliderControls: val })}
								help={__(' Enables the slider arrow/bullet controls.', 'lead-gen')}
							/>
							<RangeControl
								label={__('Per View', 'lead-gen')}
								value={sliderPageSize}
								onChange={(val) => setAttributes({ sliderPageSize: val })}
								min={1}
								max={50}
							/>
						</>
					)}

					<RangeControl
						label={__('Reviews Count', 'lead-gen')}
						value={maxReviews}
						onChange={(val) => setAttributes({ maxReviews: val })}
						min={-1}
						max={50}
					/>

					<SelectControl
						label={__('Selector', 'lead-gen')}
						value={selector}
						options={[
							{ label: __('All', 'lead-gen'), value: 'all' },
							{ label: __('Categories', 'lead-gen'), value: 'categories' },
							{ label: __('Single Posts', 'lead-gen'), value: 'name' },
						]}
						onChange={(val) => setAttributes({ selector: val })}
					/>

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

					{selector === 'name' && (
						<FormTokenField
							label={__('Choose Testimonials', 'lead-gen')}
							value={mapValuesToLabels(testimonialOptions, testimonials)}
							suggestions={testimonialOptions.map(opt => opt.label)}
							__experimentalExpandOnFocus={true}
							onChange={(tokens) => {
								setAttributes({ testimonials: mapLabelsToValues(testimonialOptions, tokens) });
							}}
						/>
					)}

					<SelectControl
						label={__('Order By', 'lead-gen')}
						value={orderBy}
						options={[
							{ label: __('Date', 'lead-gen'), value: 'date' },
							{ label: __('Name', 'lead-gen'), value: 'title' },
							{ label: __('Slug', 'lead-gen'), value: 'name' },
						]}
						onChange={(val) => setAttributes({ orderBy: val })}
					/>

					<SelectControl
						label={__('Order', 'lead-gen')}
						value={order}
						options={[
							{ label: __('Descending', 'lead-gen'), value: 'DESC' },
							{ label: __('Ascending', 'lead-gen'), value: 'ASC' },
						]}
						onChange={(val) => setAttributes({ order: val })}
					/>
				</PanelBody>

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

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

export default Edit;
