/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { PanelBody, SelectControl, ToggleControl, TextControl, RangeControl, Button } from '@wordpress/components';
import { useMemo } from '@wordpress/element';
import MultiSelect from '../../../../components/MultiSelect';
import TableSettings from '../../../../components/directory/TableSettings';

/**
 * Simple inspector controls for User Directory block
 */
export default function SimpleInspectorControls({ attributes, setAttributes, onLayoutSelectionClick }) {
	const {
		directory_layout,
		roles,
		exclude_roles,
		exclude_users,
		max_item_per_page,
		orderby,
		order,
		enable_search,
		search_placeholder,
		searchable_fields,
		enable_frontend_sorting,
		available_sort_options,
	} = attributes;

	// Get meta keys from localized data
	const metaKeys = window.wpufUserDirectory?.metaKeys || [];

	// Convert searchable_fields string to array for multi-select
	const searchableFieldsArray = useMemo(() => {
		if (!searchable_fields || searchable_fields === '') {
			return ['user_login', 'user_email', 'display_name'];
		}
		if (typeof searchable_fields === 'string') {
			return searchable_fields.split(',').map(f => f.trim()).filter(f => f);
		}
		if (Array.isArray(searchable_fields)) {
			return searchable_fields;
		}
		return ['user_login', 'user_email', 'display_name'];
	}, [searchable_fields]);

	// Handle searchable fields changes for multi-select
	const handleSearchableFieldsChange = (newSearchableFields) => {
		// Ensure newSearchableFields is always an array
		const searchableFieldsArray = Array.isArray(newSearchableFields) ? newSearchableFields : [newSearchableFields];

		// If no fields selected, default to core fields
		if (searchableFieldsArray.length === 0) {
			setAttributes({ searchable_fields: ['user_login', 'user_email', 'display_name'] });
			return;
		}

		// Keep as array for better compatibility with the API
		setAttributes({ searchable_fields: searchableFieldsArray });
	};

	// Convert roles string to array for multi-select
	const rolesArray = useMemo(() => {
		if (!roles || roles === 'all') {
			return ['all'];
		}
		if (typeof roles === 'string') {
			return roles.split(',').map(r => r.trim()).filter(r => r);
		}
		if (Array.isArray(roles)) {
			return roles;
		}
		return [];
	}, [roles]);

	// Convert exclude_roles string to array for multi-select
	const excludeRolesArray = useMemo(() => {
		if (!exclude_roles || exclude_roles === '') {
			return [];
		}
		if (typeof exclude_roles === 'string') {
			return exclude_roles.split(',').map(r => r.trim()).filter(r => r);
		}
		if (Array.isArray(exclude_roles)) {
			return exclude_roles;
		}
		return [];
	}, [exclude_roles]);

	// Convert exclude_users string to array for multi-select
	const excludeUsersArray = useMemo(() => {
		if (!exclude_users || exclude_users === '') {
			return [];
		}
		if (typeof exclude_users === 'string') {
			return exclude_users.split(',').map(u => u.trim()).filter(u => u);
		}
		if (Array.isArray(exclude_users)) {
			return exclude_users;
		}
		return [];
	}, [exclude_users]);

	// Convert available_sort_options to array for multi-select
	const availableSortOptionsArray = useMemo(() => {
		if (!available_sort_options || available_sort_options === '') {
			return ['id', 'user_login', 'user_email', 'display_name', 'user_registered'];
		}
		if (typeof available_sort_options === 'string') {
			return available_sort_options.split(',').map(o => o.trim()).filter(o => o);
		}
		if (Array.isArray(available_sort_options)) {
			return available_sort_options;
		}
		return ['id', 'user_login', 'user_email', 'display_name', 'user_registered'];
	}, [available_sort_options]);

	// Handle role changes for multi-select
	const handleRolesChange = (newRoles) => {
		// Ensure newRoles is always an array
		const rolesArray = Array.isArray(newRoles) ? newRoles : [newRoles];

		// If 'all' is selected, set roles to 'all'
		if (rolesArray.includes('all')) {
			setAttributes({ roles: 'all' });
			return;
		}

		// If no roles selected, default to 'all'
		if (rolesArray.length === 0) {
			setAttributes({ roles: 'all' });
			return;
		}

		// Convert array to comma-separated string
		const rolesString = rolesArray.join(',');
		setAttributes({ roles: rolesString });
	};

	// Handle exclude role changes for multi-select
	const handleExcludeRolesChange = (newExcludeRoles) => {
		// Ensure newExcludeRoles is always an array
		const excludeRolesArray = Array.isArray(newExcludeRoles) ? newExcludeRoles : [newExcludeRoles];

		// If no roles selected, set to empty string
		if (excludeRolesArray.length === 0) {
			setAttributes({ exclude_roles: '' });
			return;
		}

		// Convert array to comma-separated string
		const excludeRolesString = excludeRolesArray.join(',');
		setAttributes({ exclude_roles: excludeRolesString });
	};

	// Handle exclude user changes for multi-select
	const handleExcludeUsersChange = (newExcludeUsers) => {
		// Ensure newExcludeUsers is always an array
		const excludeUsersArray = Array.isArray(newExcludeUsers) ? newExcludeUsers : [newExcludeUsers];

		// If no users selected, set to empty string
		if (excludeUsersArray.length === 0) {
			setAttributes({ exclude_users: '' });
			return;
		}

		// Convert array to comma-separated string
		const excludeUsersString = excludeUsersArray.join(',');
		setAttributes({ exclude_users: excludeUsersString });
	};

	// Handle available sort options changes for multi-select
	const handleAvailableSortOptionsChange = (newAvailableSortOptions) => {
		// Ensure newAvailableSortOptions is always an array
		const availableSortOptionsArray = Array.isArray(newAvailableSortOptions) ? newAvailableSortOptions : [newAvailableSortOptions];

		// If no options selected, default to core fields
		if (availableSortOptionsArray.length === 0) {
			setAttributes({ available_sort_options: ['id', 'user_login', 'user_email', 'display_name', 'user_registered'] });
			return;
		}

		// Check if current default sort is still available
		const currentDefaultSort = orderby || 'id';
		const isCurrentDefaultAvailable = availableSortOptionsArray.includes(currentDefaultSort);

		// If current default is not available, set it to the first available option
		const newDefaultSort = isCurrentDefaultAvailable ? currentDefaultSort : availableSortOptionsArray[0];

		// Keep as array for better compatibility with the API
		setAttributes({
			available_sort_options: availableSortOptionsArray,
			orderby: newDefaultSort
		});
	};

	// Get role options for MultiSelect
	const getRoleOptions = () => {
		const dynamicRoles = window.wpufUserDirectory?.userRoles || [];

		if (dynamicRoles.length > 0) {
			// Convert array of objects to key-value object for MultiSelect
			const roleOptions = dynamicRoles.reduce((acc, role) => {
				acc[role.value] = role.label;
				return acc;
			}, {});

			return roleOptions;
		}

		// Fallback options
		return {
			'all': __('All Roles', 'wpuf-pro'),
			'administrator': __('Administrator', 'wpuf-pro'),
			'editor': __('Editor', 'wpuf-pro'),
			'author': __('Author', 'wpuf-pro'),
			'contributor': __('Contributor', 'wpuf-pro'),
			'subscriber': __('Subscriber', 'wpuf-pro'),
		};
	};

	// Get user options for MultiSelect
	const getUserOptions = () => {
		const dynamicUsers = window.wpufUserDirectory?.users || [];

		if (dynamicUsers.length > 0) {
			// Convert array of objects to key-value object for MultiSelect
			const userOptions = dynamicUsers.reduce((acc, user) => {
				acc[user.ID] = user.display_name || user.user_login;
				return acc;
			}, {});

			return userOptions;
		}

		// Fallback options - this will be populated by the PHP side
		return {};
	};

	// Get orderby options for MultiSelect
	const getOrderbyOptions = () => {
		// Core fields
		const coreFields = {
			'id': __('User ID', 'wpuf-pro'),
			'user_login': __('Username', 'wpuf-pro'),
			'user_email': __('Email', 'wpuf-pro'),
			'display_name': __('Display Name', 'wpuf-pro'),
			'user_registered': __('Registration Date', 'wpuf-pro'),
		};

		// Add usermeta keys
		const metaFields = {};
		if (Array.isArray(metaKeys)) {
			metaKeys.forEach(key => {
				metaFields[key] = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
			});
		}

		return { ...coreFields, ...metaFields };
	};

	// Get filtered orderby options for default sort (only show available options)
	const getFilteredOrderbyOptions = () => {
		const allOptions = getOrderbyOptions();
		const filteredOptions = {};

		availableSortOptionsArray.forEach(option => {
			if (allOptions[option]) {
				filteredOptions[option] = allOptions[option];
			}
		});

		return filteredOptions;
	};

	// Get searchable field options for MultiSelect
	const getSearchableFieldOptions = () => {
		// Core fields
		const coreFields = {
			'user_login': __('Username', 'wpuf-pro'),
			'user_email': __('Email', 'wpuf-pro'),
			'display_name': __('Display Name', 'wpuf-pro'),
			'first_name': __('First Name', 'wpuf-pro'),
			'last_name': __('Last Name', 'wpuf-pro'),
		};

		// Add usermeta keys
		const metaFields = {};
		if (Array.isArray(metaKeys)) {
			metaKeys.forEach(key => {
				metaFields[key] = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
			});
		}

		return { ...coreFields, ...metaFields };
	};

	return (
		<>
			<PanelBody title={__('Layout Settings', 'wpuf-pro')} initialOpen={true}>
				<Button
					variant="secondary"
					onClick={onLayoutSelectionClick}
					style={{ marginBottom: '10px' }}
				>
					{__('Choose Different Layout', 'wpuf-pro')}
				</Button>
			</PanelBody>

			<PanelBody title={__('Display Options', 'wpuf-pro')} initialOpen={false}>
				{/* Enhanced Role Selection */}
				<div className="wpuf-mb-4">
					<div className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-mb-2">
						<label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
							{__('User Roles', 'wpuf-pro')}
						</label>
					</div>

					<MultiSelect
						options={getRoleOptions()}
						value={rolesArray}
						onChange={handleRolesChange}
						placeholder={__('Select user roles...', 'wpuf-pro')}
					/>
				</div>

				<div className="wpuf-mb-4">
					<div className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-mb-2">
						<label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
							{__('Exclude Roles', 'wpuf-pro')}
						</label>
					</div>

					<MultiSelect
						options={getRoleOptions()}
						value={excludeRolesArray}
						onChange={handleExcludeRolesChange}
						placeholder={__('Exclude user roles...', 'wpuf-pro')}
					/>
				</div>

				<div className="wpuf-mb-4">
					<div className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-mb-2">
						<label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
							{__('Exclude Users', 'wpuf-pro')}
						</label>
					</div>

					<MultiSelect
						options={getUserOptions()}
						value={excludeUsersArray}
						onChange={handleExcludeUsersChange}
						searchable={true}
						placeholder={__('Exclude specific users...', 'wpuf-pro')}
					/>
				</div>

				<RangeControl
					label={__('Max Profiles Per Page', 'wpuf-pro')}
					value={max_item_per_page}
					onChange={(value) => setAttributes({ max_item_per_page: value })}
					min={1}
					max={50}
					__next40pxDefaultSize={true}
					__nextHasNoMarginBottom={true}
				/>

				{/* Only show Users Per Row for non-table layouts */}
				{directory_layout !== 'table' && (
					<RangeControl
						label={__('Users Per Row', 'wpuf-pro')}
						value={attributes.usersPerRow}
						onChange={(value) => setAttributes({ usersPerRow: value })}
						min={1}
						max={4}
						__next40pxDefaultSize={true}
						__nextHasNoMarginBottom={true}
					/>
				)}
			</PanelBody>

			<PanelBody title={__('Search Options', 'wpuf-pro')} initialOpen={false}>
				<ToggleControl
					label={__('Enable Search', 'wpuf-pro')}
					checked={enable_search}
					onChange={(value) => setAttributes({ enable_search: value })}
					__nextHasNoMarginBottom={true}
				/>

				{enable_search && (
					<>
						<TextControl
							label={__('Search Placeholder', 'wpuf-pro')}
							value={search_placeholder}
							onChange={(value) => setAttributes({ search_placeholder: value })}
							__next40pxDefaultSize={true}
							__nextHasNoMarginBottom={true}
						/>

						<div className="wpuf-mb-4">
							<div className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-mb-2">
								<label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
									{__('Searchable Fields', 'wpuf-pro')}
								</label>
							</div>

							<MultiSelect
								options={getSearchableFieldOptions()}
								value={searchableFieldsArray}
								onChange={handleSearchableFieldsChange}
                                sortable={true}
								searchable={true}
								placeholder={__('Select searchable fields...', 'wpuf-pro')}
							/>

							<p className="wpuf-text-sm wpuf-text-gray-500 wpuf-mt-1">
								{__('Select which fields should be searchable. Users can search across these fields.', 'wpuf-pro')}
							</p>
						</div>
					</>
				)}
			</PanelBody>

			<PanelBody title={__('Sorting Options', 'wpuf-pro')} initialOpen={false}>
				<ToggleControl
					label={__('Enable Frontend Sorting', 'wpuf-pro')}
					checked={enable_frontend_sorting}
					onChange={(value) => setAttributes({ enable_frontend_sorting: value })}
					help={__('When enabled, visitors can sort the user directory from the frontend. When disabled, only the default sorting will be applied.', 'wpuf-pro')}
					__nextHasNoMarginBottom={true}
				/>

				{enable_frontend_sorting && (
					<>
						<div className="wpuf-mb-4">
							<div className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-mb-2">
								<label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
									{__('Available Sort Options', 'wpuf-pro')}
								</label>
							</div>

							<MultiSelect
								options={getOrderbyOptions()}
								value={availableSortOptionsArray}
								sortable={true}
								onChange={handleAvailableSortOptionsChange}
								placeholder={__('Select sorting options...', 'wpuf-pro')}
							/>
						</div>
					</>
				)}

				<SelectControl
					label={__('Default Sort On', 'wpuf-pro')}
					value={orderby}
					options={Object.entries(getFilteredOrderbyOptions()).map(([value, label]) => ({
						value,
						label
					}))}
					onChange={(value) => setAttributes({ orderby: value })}
					help={__('This will be the default field used for sorting when visitors first view the directory.', 'wpuf-pro')}
					__next40pxDefaultSize={true}
					__nextHasNoMarginBottom={true}
				/>

				<SelectControl
					label={__('Default Sort Order', 'wpuf-pro')}
					value={order}
					options={[
						{ value: 'asc', label: __('Ascending (A-Z)', 'wpuf-pro') },
						{ value: 'desc', label: __('Descending (Z-A)', 'wpuf-pro') },
					]}
					onChange={(value) => setAttributes({ order: value })}
					help={__('This will be the default sort order when visitors first view the directory.', 'wpuf-pro')}
					__next40pxDefaultSize={true}
					__nextHasNoMarginBottom={true}
				/>
			</PanelBody>

            {/* Table Settings Panel - Only show when layout is table */}
            {directory_layout === 'table' && (
                <PanelBody title={__('Table Settings', 'wpuf-pro')} initialOpen={true}>
                    <TableSettings
                        formData={attributes}
                        setFormData={(newData) => setAttributes(newData)}
                    />
                </PanelBody>
            )}
		</>
	);
}
