import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { Modal, Button, PanelBody, __experimentalScrollable as Scrollable, QueryControls, ToggleControl, SelectControl, TextareaControl, CheckboxControl, } from '@wordpress/components';
import { useSelect, select } from '@wordpress/data';
import { useState, useEffect } from '@wordpress/element';
import { AddLabelForm } from './AddLabelForm';
import { BoardMember } from './BoardMember';
import NormalPeople from './NormalPeople';
import apiFetch from '@wordpress/api-fetch';

import './editor.scss';
import EditUserForm from './EditUserForm';

export default function Edit({ attributes, setAttributes }) {
	const { checkedCategories, displayVaralla, displayDropdown, displaySearchOption, postType, numberOfPosts, displayFeaturedImage, displayName, displayTitle, displayDesignation, displayPhone, categories, displayEmail, displayCity, displayProfileLink, displaySocialLink, displayHomeLink, displayRankNumber, selectedTitles } = attributes;

	const [searchTerm, setSearchTerm] = useState('');
	const [filteredPeople, setFilteredPeople] = useState([]);

	const [delSearchTerm, setDelSearchTerm] = useState('');
	const [filteredMembers, setFilteredMembers] = useState([]);
	//Add Label Modal
	const [isOpen, setOpen] = useState(false);
	const openModal = () => setOpen(true);
	const closeModal = () => setOpen(false);

	const [selectedPostId, setSelectedPostId] = useState(null);
	//Edit User Modal
	const [isEditOpen, setEditOpen] = useState(false);
	const openEditModal = (postId) => {
		setSelectedPostId(postId);
		setEditOpen(true);
	  }
	const closeEditModal = () => setEditOpen(false);

	const onHandleValueChange = (value) => {
		setAttributes({ selectedValue: value });
	};
	const [formData, setFormData] = useState([]);
	const [formEditData, setEditFormData] = useState([]);

	const handleSubmit = (data) => {
		setFormData(data);
	};
	const handleEditSubmit = (data) => {
		setEditFormData(data);
	};

	const onDisplayFeaturedImageChange = (value) => {
		setAttributes({ displayFeaturedImage: value });
	};
	const onDisplayNameChange = (value) => {
		setAttributes({ displayName: value });
	};
	const onDisplayTitleChange = (value) => {
		setAttributes({ displayTitle: value });
	};
	const onDisplayDesignationChange = (value) => {
		setAttributes({ displayDesignation: value });
	};
	const onDisplayvarallaChange = (value) => {
		setAttributes({ displayVaralla: value });
	};
	const onDisplayPhoneChange = (value) => {
		setAttributes({ displayPhone: value });
	};
	const onDisplayEmailChange = (value) => {
		setAttributes({ displayEmail: value });
	};
	const onDisplayCityChange = (value) => {
		setAttributes({ displayCity: value });
	};
	const onDisplayProfileLinkChange = (value) => {
		setAttributes({ displayProfileLink: value });
	};
	const onDisplaySocialLinkChange = (value) => {
		setAttributes({ displaySocialLink: value });
	};
	const onDisplayHomeLinkChange = (value) => {
		setAttributes({ displayHomeLink: value });
	};
	const onDisplayRankNumberChange = (value) => {
		setAttributes({ displayRankNumber: value });
	};
	const onChangeSearchOption = (value) => {
		setAttributes({ displaySearchOption: value });
	};
	const onChangeDropdownDisplay = (value) => {
		setAttributes({ displayDropdown: value });
	};
	const onChangeTabView = (value) => {
		setAttributes({ displayTabView: value });
	};
	const [sortedMembers, setSortedMembers] = useState([]);

	const postTypes = useSelect((select) => {
		return select('core').getPostTypes({ per_page: -1 });
	}, []);

	const catIds = categories && categories.length > 0 ? categories.map((cat) => cat.id) : [];

	const postTypeTaxonomy = postTypes && postTypes.length
		? postTypes.find((type) => type.slug === postType)?.taxonomies[0] || 'category'
		: '';

	const items = useSelect(
		(select) => {
			if (selectedTitles && selectedTitles.length > 0) {
				const titleArgs = {
					per_page: -1,
					_embed: true,
				};

				return select('core').getEntityRecords('postType', postType, titleArgs);
			}
			const otherQueryArgs = {
				per_page: numberOfPosts,
				_embed: true,
			};

			postType === 'post' ? (otherQueryArgs.categories = catIds) : (otherQueryArgs[postTypeTaxonomy] = catIds);

			return select('core').getEntityRecords('postType', postType, otherQueryArgs);
		},
		[postType, catIds, postTypeTaxonomy, numberOfPosts, selectedTitles]
	);
	//For Post
	const allCats = useSelect(
		(select) => {
			return postTypeTaxonomy
				? select('core').getEntityRecords('taxonomy', postTypeTaxonomy, {
					per_page: -1,
				})
				: [];
		},
		[postTypeTaxonomy]
	);

	const catSuggestions = {};
	//For other post type
	if (allCats) {
		for (let i = 0; i < allCats.length; i++) {
			const cat = allCats[i];
			catSuggestions[cat.name] = cat;
		}
	}

	const onCategoryChange = (values) => {
		const hasNoSuggestions = values.some((value) => typeof value === 'string' && !catSuggestions[value]);
		if (hasNoSuggestions) return;

		const updatesCats = values.map((token) => {
			return typeof token === 'string' ? catSuggestions[token] : token;
		});

		setAttributes({ categories: updatesCats });
	};

	const onSelectTitles = (selected) => {
		const titleObjs = selected.map(title => {
			const foundpost = allPostTitles.find(post => post.title === title);
			return foundpost ? foundpost : { id: null, title: title };
		});
		setAttributes({ selectedTitles: titleObjs });
	};
	const filteredItems = (items || []).filter(item =>
		!selectedTitles || selectedTitles.length === 0 || selectedTitles.some(titleObj => titleObj.title === item.title.rendered)
	);

	const allPostTitles = useSelect(
		(select) => {
			const baseArgs = { per_page: -1 };

			if (catIds && catIds.length > 0) {
				baseArgs['categories'] = catIds;
			}

			const allPosts = select('core').getEntityRecords('postType', postType, baseArgs);
			return allPosts ? allPosts.map(post => ({ id: post.id, title: post.title.rendered })) : [];
		},
		[catIds]
	);

	function sortPostsBySelectedTitles(posts, selectedTitles) {
		const sortedPosts = [];

		selectedTitles.forEach((titleObj) => {
			const matchingPost = posts.find((post) => titleObj.title === post.title.rendered);
			if (matchingPost) {
				sortedPosts.push(matchingPost);
			}
		});

		posts.forEach((post) => {
			if (!selectedTitles.some((titleObj) => titleObj.title === post.title.rendered)) {
				sortedPosts.push(post);
			}
		});

		return sortedPosts;
	}
	const filteredPosts = sortPostsBySelectedTitles(filteredItems, selectedTitles);

	const handleCheckboxChange = (categoryId) => {
		const updatedCheckedCategories = checkedCategories.includes(categoryId);
		setAttributes({
			checkedCategories: updatedCheckedCategories ?
				checkedCategories.filter(id => id !== categoryId) :
				[...checkedCategories, categoryId]
		});
	};

	const addPersons = (personID) => {
		const categoryID = categories.length > 0 ? categories[0].id : null;
		const categoryName = categories.length > 0 ? categories[0].value : null;
		const taxonomySlug = 'group';

		if (!categoryID) {
			console.error('Please specify a category ID before adding the person.');
			return;
		}

		apiFetch({
			path: `/wp/v2/person/${personID}`,
			method: 'GET',
		}).then(existingPersonData => {
			const existingCategories = existingPersonData[taxonomySlug] || [];
			if (!existingCategories.includes(categoryID)) {
				existingCategories.push(categoryID);

				apiFetch({
					path: `/wp/v2/person/${personID}`,
					method: 'PATCH',
					data: {
						[taxonomySlug]: existingCategories,
					},
				}).then(response => {
					const updatedCategories = [...categories, { id: categoryID, value: categoryName }];
					setAttributes({ categories: updatedCategories });
				}).catch(error => {
					console.error('Error adding person to category:', error);
				});
			} else {
				console.log(`Person ${personID} is already in category ${categoryID}`);
			}
		}).catch(error => {
			console.error('Error fetching person data:', error);
		});
	};

	const deletePerson = (personID) => {
		const categoryID = categories.length > 0 ? categories[0].id : null;
		const categoryName = categories.length > 0 ? categories[0].value : null;
		const taxonomySlug = 'group';
		wp.apiFetch({
			path: `/wp/v2/person/${personID}`,
			method: 'PATCH',
			data: {
				[taxonomySlug]: [],
			},
		}).then(response => {
			// console.log(`Person ${personID} removed from all categories`, response);
			const updatedCategories = [...categories, { id: categoryID, value: categoryName }];
			setAttributes({ categories: updatedCategories });
		}).catch(error => {
			console.error('Error deleting person from categories:', error);
		});
	};

	const uniqueCategories = categories && categories.filter((category, index, self) =>
		index === self.findIndex((c) => c.id === category.id));

	const logNestedCategories = (parentCategoryId, depth = 0) => {
		const childCategories = select('core').getEntityRecords('taxonomy', 'group', {
			parent: parentCategoryId,
			hide_empty: true,
			per_page: -1,
		});

		if (!childCategories || childCategories.length === 0) {
			return [];
		}
		const nestedCategories = [];
		childCategories.forEach(category => {
			nestedCategories.push({ ...category, depth });
			const nestedChildren = logNestedCategories(category.id, depth + 1);
			nestedCategories.push(...nestedChildren);
		});
		return nestedCategories;
	};

	const childCategories = uniqueCategories && uniqueCategories[0]?.id
		? logNestedCategories(uniqueCategories[0].id)
		: [];

	const allChildIds = childCategories.map(category => category.id);
	// const sortedMembers = filteredPosts;
	useEffect(() => {
		let newSortedMembers = checkedCategories.length > 0
			? filteredPosts.filter(post => post.group.some(groupId => checkedCategories.includes(groupId)))
			: filteredPosts;
		if (newSortedMembers.length === 0) {
			newSortedMembers = filteredPosts;
		}
		setSortedMembers(newSortedMembers);
	}, [checkedCategories, filteredPosts]);

	const remainingPeoples = allPostTitles.filter(post => (
		!sortedMembers.some(member => member.id === post.id)
	));
	//Search People
	const handleSearchChange = (e) => {
		setSearchTerm(e.target.value);
	}
	useEffect(() => {
		if (searchTerm.trim() === '') {
			setFilteredPeople(remainingPeoples);
		} else {
			const filtered = remainingPeoples.filter(post =>
				post.title.toLowerCase().includes(searchTerm.toLowerCase())
			);
			setFilteredPeople(filtered);
		}
	}, [searchTerm, remainingPeoples]);

	// Function to handle delete search input change
	const handleDelSearchChange = (e) => {
		setDelSearchTerm(e.target.value);
	}

	// Function to filter members based on delete search term
	useEffect(() => {
		if (delSearchTerm.trim() === '') {
			// If delete search term is empty, show all members
			setFilteredMembers(sortedMembers);
		} else {
			// Filter members based on delete search term
			const filtered = sortedMembers.filter(post =>
				post.title.rendered.toLowerCase().includes(delSearchTerm.toLowerCase())
			);
			setFilteredMembers(filtered);
		}
	}, [delSearchTerm, sortedMembers]);
	return (
		<div {...useBlockProps()}>
			<>
				{isOpen && (
					<Modal title="Add Person Level" onRequestClose={closeModal}>
						<AddLabelForm closeModal={closeModal} attributes={attributes} sortedMembers={sortedMembers} allPostTitles={allPostTitles} handleSubmit={handleSubmit} />
					</Modal>
				)}
				{isEditOpen && (
					<Modal title="Edit People" onRequestClose={closeEditModal}>
						<EditUserForm attributes={attributes} postId={selectedPostId} closeEditModal={closeEditModal}  sortedMembers={sortedMembers} setSortedMembers={setSortedMembers} />
					</Modal>
				)}
			</>
			<InspectorControls>
				<PanelBody>
					<QueryControls
						categorySuggestions={catSuggestions}
						selectedCategories={uniqueCategories}
						onCategoryChange={onCategoryChange}
					/>
					<SelectControl onChange={onHandleValueChange}
						label={__('No of Columns', 'artcloud-blocks')} >
						<option value='6'>Valitse</option>
						<option value='12'>1</option>
						<option value='6'>2</option>
						<option value='4'>3</option>
						<option value='3'>4</option>
					</SelectControl>
					<ToggleControl
						label={displayDropdown ? __('Dropdown View', 'artcloud-blocks') : __('Tab View', 'artcloud-blocks')}
						help={
							displayDropdown
								? __('Dropdown View', 'artcloud-blocks')
								: __('Tab View', 'artcloud-blocks')
						}
						checked={displayDropdown}
						onChange={onChangeDropdownDisplay}
					/>
					<CheckboxControl
						label={__('Display Search Option', 'artcloud-blocks')}
						checked={displaySearchOption}
						onChange={onChangeSearchOption}
					/>
					<PanelBody title={__('Add/Remove People', 'artcloud-blocks')} initialOpen={false}>
						<label className="components-form-token-field__label">{__('Add People to Group', 'artcloud-blocks')}</label>
						<p><strong>{__('Search People', 'artcloud-blocks')}</strong></p>
						<input type="text" name="addSearchPeople" id="addSearchPeople" value={searchTerm} onChange={handleSearchChange} />
						<p><strong>{__('Total People', 'artcloud-blocks')}: {filteredPeople.length}</strong></p>
						<Scrollable
							style={{ maxHeight: 200 }}>
							<div style={{ height: 500 }}>
								<ul>
									{filteredPeople.map(post => (
										<li key={post.id} className='artcloud-peopleAdd'>
											<div>{post.title}</div>
											<div>
												<a href="#" className="artcloud-people-add" onClick={() => addPersons(post.id)}>
													<span className="dashicons dashicons-plus-alt"></span>
												</a>
											</div>
										</li>
									))}
								</ul></div>
						</Scrollable>
						<hr />
						<label className="components-form-token-field__label">{__('People Added to Group', 'artcloud-blocks')}</label>
						<p><strong>{__('Search People', 'artcloud-blocks')}</strong></p>
						<input type="text" name="delSearchPeople" id="delSearchPeople" value={delSearchTerm} onChange={handleDelSearchChange} />
						<p><strong>{__('Total People', 'artcloud-blocks')}: {filteredMembers.length}</strong></p>
						<Scrollable
							style={{ maxHeight: 200 }}>
							<div style={{ height: 500 }}>
								<ul>
									{filteredMembers.map(post => (
										<li key={post.id} className='artcloud-peopleDelete'>
											<div>{post.title.rendered}</div>
											<div>
												<a href="#" className="artcloud-people-delete" onClick={() => deletePerson(post.id)}>
													<span class="dashicons dashicons-trash"></span>
												</a>
												<a href="#" className="artcloud-people-edit" onClick={() => openEditModal(post.id)}>
													<span class="dashicons dashicons-edit-page"></span>
												</a>
											</div>
										</li>
									))}
								</ul></div>
						</Scrollable>
					</PanelBody>
					<PanelBody title={__('Show/Hide Information', 'artcloud-blocks')} initialOpen={false}>
						<CheckboxControl
							label={__('Profile Image', 'artcloud-blocks')}
							checked={displayFeaturedImage}
							onChange={onDisplayFeaturedImageChange}
						/>
						<CheckboxControl
							label={__('Full Name', 'artcloud-blocks')}
							checked={displayName}
							onChange={onDisplayNameChange}
						/>
						<CheckboxControl
							label={__('Designation', 'artcloud-blocks')}
							checked={displayDesignation}
							onChange={onDisplayDesignationChange}
						/>
						<CheckboxControl
							label={__('Varalla', 'artcloud-blocks')}
							checked={displayVaralla}
							onChange={onDisplayvarallaChange}
						/>
						<CheckboxControl
							label={__('Title', 'artcloud-blocks')}
							checked={displayTitle}
							onChange={onDisplayTitleChange}
						/>
						<CheckboxControl
							label={__('Phone', 'artcloud-blocks')}
							checked={displayPhone}
							onChange={onDisplayPhoneChange}
						/>
						<CheckboxControl
							label={__('Email', 'artcloud-blocks')}
							checked={displayEmail}
							onChange={onDisplayEmailChange}
						/>
						<CheckboxControl
							label={__('Profile Link', 'artcloud-blocks')}
							checked={displayProfileLink}
							onChange={onDisplayProfileLinkChange}
						/>
						<CheckboxControl
							label={__('Home Link', 'artcloud-blocks')}
							checked={displayHomeLink}
							onChange={onDisplayHomeLinkChange}
						/>
						<CheckboxControl
							label={__('Social Link', 'artcloud-blocks')}
							checked={displaySocialLink}
							onChange={onDisplaySocialLinkChange}
						/>
						<CheckboxControl
							label={__('City', 'artcloud-blocks')}
							checked={displayCity}
							onChange={onDisplayCityChange}
						/>

						<CheckboxControl
							label={__('Rank Number', 'artcloud-blocks')}
							checked={displayRankNumber}
							onChange={onDisplayRankNumberChange}
						/>
					</PanelBody>
					<PanelBody title={__('Add New Level', 'artcloud-blocks')} initialOpen={false}>
						<Button variant="secondary" onClick={openModal}>
							{__('Add Level', 'artcloud-blocks')}
						</Button>
					</PanelBody>
					<PanelBody title={__('Sub Groups', 'artcloud-blocks')} initialOpen={false}>
						<Scrollable
							style={{ maxHeight: 200 }}>
							<hr />
							<label className="components-form-token-field__label">{__('All Subgroups', 'artcloud-blocks')}</label>
							<div style={{ height: 500 }}>
								<ul>
									{childCategories.length > 0 ? (
										childCategories.map((category) => (
											<li key={category.id}>
												{`${'\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0'.repeat(category.depth)}`}
												<input
													type="checkbox"
													id={category.id}
													defaultChecked={checkedCategories.includes(category.id)}
													onChange={() => handleCheckboxChange(category.id)}
												/>
												{`${category.name}`}
											</li>
										))
									) : (
										<li>{__('No Subgroups', 'artcloud-blocks')}</li>
									)}
								</ul>
							</div>
						</Scrollable>
					</PanelBody>
				</PanelBody>
			</InspectorControls>
			<BoardMember attributes={attributes} sortedMembers={sortedMembers} formData={formData} formEditData={formEditData} />
			{/*<NormalPeople attributes={attributes} sortedItems={sortedItems} /> */}
		</div>
	);
}
