import { __ } from '@wordpress/i18n';
import { useSelect } from "@wordpress/data";
import { RichText } from "@wordpress/block-editor";
import { useState } from "@wordpress/element";
import { SocialIcons } from "./AddSVGS";
export const BoardMember = ({ attributes, sortedMembers, formData, setAttributes }) => {
	const [rows, setRows] = useState([{ 0: "", 1: "", 2: "", 3: "" }]);
	const {
		displayFeaturedImage,
		displayName,
		displayTitle,
		displayDesignation,
		displayPhone,
		categories,
		displayEmail,
		displayCity,
		displayProfileLink,
		displaySocialLink,
		displayHomeLink,
		displayRankNumber,
		selectedValue,
		displayVaralla,
		memberTitle,
		memberDesc
	} = attributes;
	const onChangeMemberTitle = (value) => {
		setAttributes({ memberTitle: value });
	}
	const onChangeMemeberDesc = (value) => {
		setAttributes({ memberDesc: value });
	}
	const categoryID =
		categories && categories.length > 0 ? categories && categories[0].id : null;
	const taxonomy = useSelect((select) => {
		return select("core").getEntityRecords("taxonomy", "group", {
			include: [categoryID],
		});
	});
	const rank_info_db = taxonomy && taxonomy[0] && taxonomy[0].rank_information;

	const flatArray = formData.flatMap((item) => {
		if (typeof item === "object" && !Array.isArray(item)) {
			return Object.values(item);
		} else {
			return item;
		}
	});

	// console.log(flatArray);

	const numberOfColumns = 4;

	const rank_info_form_data = {};

	for (let i = 0; i < flatArray.length; i += numberOfColumns) {
		const subArray = flatArray.slice(i, i + numberOfColumns);
		rank_info_form_data[i / numberOfColumns] = subArray;
	}

	let rank_infos = {};
	if (rank_info_db && rank_info_db !== 'a:0:{}' && rank_info_db !== 'a:1:{i:0;a:0:{}}') {
		function unserialize(data) {
			return data.match(/s:([0-9]+):"(.*?)";/g).map(function (s) {
				var m = s.match(/s:([0-9]+):"(.*?)";/);
				if (m) {
					if (m[2].startsWith("a:") || m[2].startsWith("O:")) {
						return JSON.parse(deserializeValue(m[2]));
					} else {
						return m[2];
					}
				} else {
					return s;
				}
			});
		}

		function deserializeValue(value) {
			var deserialized = unserialize(value);
			return deserialized.length === 1 ? deserialized[0] : deserialized;
		}

		const deserializedMetadata = unserialize(rank_info_db);

		// Convert the flat array to a JSON object
		for (let i = 0; i < deserializedMetadata.length; i += 4) {
			rank_infos[i / 4] = deserializedMetadata.slice(i, i + 4);
		}
	} else {
		console.warn("Taxonomy or rank_information is null.");
	}
	let rank_info = {};
	function empty(obj) {
		return Object.keys(obj).length === 0 && obj.constructor === Object;
	}

	if (!empty(rank_info_form_data)) {
		rank_info = rank_info_form_data;
	} else {
		rank_info = rank_infos;
	}
	// console.log(categories);
	return (
		<>
			{categories && categories.length > 0 ? (
				<>
					<h3 className="people-block-title">{categories && categories[0] ? categories[0].name : __("Group Name", "artcloud-blocks")}</h3>
					<p className="people-block-desc">{categories && categories[0] ? categories[0].description : __("Group description not added", "artcloud-blocks")}</p>
					<div className="row artcloud-row row-1">
						{sortedMembers &&
							sortedMembers.map((person, index) => {
								const featuredImage =
									person._embedded &&
									person._embedded["wp:featuredmedia"] &&
									person._embedded["wp:featuredmedia"].length > 0 &&
									person._embedded["wp:featuredmedia"][0];

								return (
									<React.Fragment key={person.id}>
										<div className={`col-${selectedValue || '12'} ${selectedValue === '4' || selectedValue === '3' ? 'vertical' : 'horizontal'}`} key={person.id} style={{
											order: (
												Array.from({
													length: Math.max(rows.length, Object.keys(rank_info).length),
												})
													.map((_, index) =>
														rank_info[index] &&
														rank_info[index][2] == person.id && (rank_info[index][0])
													)
													.find((value) => value !== false) || 1000000
											)
										}}>
											<div className={`artcloud-peoples-item ${person.id}`}>
												<div className="artcloud-peoples-image">
													{displayFeaturedImage &&
														featuredImage &&
														featuredImage.media_details &&
														featuredImage.media_details.sizes &&
														featuredImage.media_details.sizes.thumbnail && (
															<img
																src={
																	featuredImage.media_details.sizes.thumbnail
																		.source_url
																}
																alt={featuredImage.alt_text}
															/>
														)}
												</div>
												<div className="artcloud-peoples-content">
													<h5>
														<a
															href={
																displayProfileLink &&
																(person.link ? person.link : "#")
															}
														>
															{displayName &&
																person.title &&
																person.title.rendered}
														</a>
													</h5>
													{displayDesignation &&
														<p>
															{Array.from({
																length: Math.max(rows.length, Object.keys(rank_info).length),
															}).map(
																(_, index) =>
																	rank_info[index] &&
																	rank_info[index][2] == person.id && (rank_info[index][1])
															)}
														</p>
													}
													{displayTitle &&
														<p className="people_title">
															{person.person_meta_fields.people_title}
														</p>
													}
													{displayCity &&
													<p className="people_city">
															{person.person_meta_fields.people_city}
															</p>
														}
														{displayPhone &&
													<p className="people_phone">
															{person.person_meta_fields.people_phone}
															</p>
														}
														{displayEmail &&
													<p className="people_email">
															{person.person_meta_fields.people_email}
															</p>
														}
													<div className="social-link">
														{displayHomeLink && (
															<a className="people_home"
																href={`https://${person.person_meta_fields.home}`}
															>
																{SocialIcons.homesocial}
															</a>
														)}
														{displaySocialLink && (
															<div>
																<a className='people_twitter'
																	href={`https://${person.person_meta_fields.twitter}`}
																>
																	{SocialIcons.twitter}
																</a>
																<a className='people_facebook'
																	href={`https://${person.person_meta_fields.facebook}`}
																>
																	{SocialIcons.facebook}
																</a>
																<a className='people_linkedin'
																	href={`https://${person.person_meta_fields.linkedin}`}
																>
																	{SocialIcons.linkedin}
																</a>
																<a className='people_instagram'
																	href={`https://${person.person_meta_fields.instagram}`}
																>
																	{SocialIcons.instagram}
																</a>
															</div>
														)}
														{displayRankNumber && (
															<h6 className="people_rank">{person.person_meta_fields.rank_number}</h6>
														)}
													</div>
													{displayVaralla && (
														<div className="artcloud-peoples-name">
															{Array.from({
																length: Math.max(rows.length, Object.keys(rank_info).length),
															}).map(
																(_, index) =>
																	rank_info[index] &&
																	rank_info[index][2] == person.id &&
																	(<><h6>Varalla </h6>
																		<p>{wp.data.select('core').getEntityRecord('postType', 'person', rank_info[index][3])?.title?.rendered || ''}
																		</p></>
																	)
															)}
														</div>
													)}
												</div>
											</div>
										</div>
									</React.Fragment>
								);
							})}
					</div>
				</>
			) : (
				<p>{__('Select a category first', 'artcloud-blocks')}<hr /></p>
			)
			}
		</>
	)
};
