import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import Icon from '../../utils/Icon';
import { formatNumber } from '../../utils/formatting';
import debounce from 'lodash/debounce';
import usePostsStore from '../../store/usePostsStore';
import AsyncSelectInput from '@/components/Inputs/AsyncSelectInput';
import FieldWrapper from '@/components/Fields/FieldWrapper';
import { __ } from '@wordpress/i18n';

/**
 * SelectField component
 *
 * @param {Object} field      - Provided by react-hook-form's Controller.
 * @param {Object} fieldState - Contains validation state.
 * @param {string} label      - Field label.
 * @param {string} help       - Help text for the field.
 * @param {string} context    - Contextual information for the field.
 * @param {string} className  - Additional Tailwind CSS classes.
 * @param {Object} props      - Additional props (including options array).
 * @return {JSX.Element}
 */
const SelectPageField =

	// fallow-ignore-next-line complexity
	({ field, fieldState, label, help, context, className, ...props }) => {
		const inputId = props.id || field?.name;

		const { fetchPosts } = usePostsStore();
		const [ search, setSearch ] = useState( '' );
		const maxSelections = props.maxSelections || 1;

		const posts = useQuery({
			queryKey: [ 'defaultPosts', search ],
			queryFn: () => fetchPosts( search )
		});

		// Load options function with debounce
		const loadOptions = debounce( async( input, callback ) => {
			setSearch( input );
			const data = await fetchPosts( input );
			callback( data );
		}, 500 );

		const selectValue = field?.value || '';

		return (
			<FieldWrapper
				label={label}
				help={help}
				error={fieldState?.error?.message}
				context={context}
				className={className}
				inputId={inputId}
				required={props.required}
				recommended={props.recommended}
				disabled={props.disabled}
				{...props}
			>
				<AsyncSelectInput
					onChange={( e ) => {
						if ( 1 === maxSelections ) {
							if ( ! e?.value ) {
								props.onChange( '' );
							} else {
								props.onChange( e.value );
							}
						} else {
							const values = e ? e.map( ( item ) => item.value ) : [];
							props.onChange( values );
						}
					}}
					isLoading={posts.isFetching}
					name="selectPage"
					value={selectValue}
					maxSelections={maxSelections}
					defaultInputValue={selectValue}
					defaultOptions={posts.data || []}
					loadOptions={loadOptions}
					components={{ Option: OptionLayout }}
				/>
				{props.goal && props.goal.is_draft && (
					<p className="mt-1.5 text-xs text-text-gray-light">
						{__( 'The post is in draft, once it is published the url will be updated here.', 'burst-statistics' )}
					</p>
				)}
			</FieldWrapper>
		);
	};

SelectPageField.displayName = 'SelectPageField';

export default SelectPageField;

// Option layout component
const OptionLayout = ({ innerProps, innerRef, data }) => {
	const r = data;
	return (
		<article
			ref={innerRef}
			{...innerProps}
			className="flex items-center justify-between p-2 hover:bg-gray-100 cursor-pointer transition-colors duration-200"
		>
			<div className="flex items-center">
				<h6 className="text-sm font-medium text-text-black">{r.label}</h6>
				{'Untitled' !== r.post_title && (
					<>
						<span className="mx-2 text-text-gray-light"> - </span>
						<p className="text-sm text-text-gray-light">{r.post_title}</p>
					</>
				)}
			</div>
			{0 < r.pageviews && (
				<div className="flex items-center gap-1 text-xs text-text-gray-light">
					<Icon name={'eye'} size={12} />
					<span>{formatNumber( r.pageviews )}</span>
				</div>
			)}
		</article>
	);
};
