import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Button } from '@wordpress/components';
import { useEffect, useState } from '@wordpress/element';

export const AddLabelForm = ({ attributes, setAttributes, sortedMembers, handleSubmit, closeModal }) => {
	const { categories, selectedTitles } = attributes;
	const [rows, setRows] = useState([{ 0: '', 1: '', 2: '', 3: '' }]);
	const [rankInfo, setRankInfo] = useState([{}]);

	useEffect(() => {
		const fetchData = async () => {
			const catID = categories && categories.length > 0 ? categories && categories[0].id : null;
			const taxonomy = await apiFetch({
				path: `/wp/v2/group/${catID}`,
			});
			const rank_info_db = taxonomy && taxonomy.rank_information ? taxonomy.rank_information : 'a:0:{}';
			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;
				}
				if (rank_info_db && rank_info_db !== 'a:0:{}') {
					const deserializedMetadata = unserialize(rank_info_db);
					let updatedRankInfo = [];
					for (let i = 0; i < deserializedMetadata.length; i += 4) {
						updatedRankInfo.push(deserializedMetadata.slice(i, i + 4));
					}
					setRankInfo(updatedRankInfo);
				} else {
					console.warn('Taxonomy or rank_information is null.');
				}
			}
		};

		fetchData();
	}, [categories]);

	const handleChange = (index, field, value) => {
		const newRows = [...rows];
		newRows[index] = { ...newRows[index], [field]: value };
		setRows(newRows);

		const newRankInfo = [...rankInfo];
		if (newRankInfo[index]) {
			newRankInfo[index] = { ...newRankInfo[index], [field]: value };
		} else {
			newRankInfo[index] = { [field]: value };
		}
		setRankInfo(newRankInfo);
	};

	const handleAddRow = () => {
		const newRow = { 0: '', 1: '', 2: '', 3: '' };
		setRows([...rows, newRow]);
	};

	const handleRemoveRow = (index) => {
		const newRows = [...rows];
		newRows.splice(index, 1);
		setRows(newRows);
		const newRankInfo = [...rankInfo];
		newRankInfo.splice(index, 1);
		setRankInfo(newRankInfo);
	};

	const handleFormSubmit = async (e) => {
		e.preventDefault();
		let formData = Array.from({ length: Math.max(rows.length, rankInfo.length) }).flatMap((_, index) => (
			rankInfo[index] || (rows[index] ? rows[index] : '')
		));
		try {
			const saveResponse = await saveTermMeta(formData);
			closeModal();
			// console.log('Save Response:', saveResponse);
		} catch (error) {
			console.error('Error saving term meta or fetching posts:', error);
		}
		const newData = formData;
		handleSubmit(newData);
		// console.log('Form Data:', formData);
	};

	const saveTermMeta = async (rankInformation) => {
		try {
			const termId = categories && categories.length > 0 ? categories[0].id : null;
			const response = await apiFetch({
				path: '/persons_info/v1/save_rank_information/',
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					term_id: termId,
					rank_information: rankInformation,
				}),
			});
			return response;
		} catch (error) {
			throw error;
		}
	};

	return (
		<>
			<form onSubmit={handleFormSubmit}>
				{Array.from({ length: Math.max(rows.length, rankInfo.length) }).map((_, index) => {
					const isExistingRow = index < rankInfo.length;
					const rankInfoData = isExistingRow ? rankInfo[index] : {};
					const rowData = isExistingRow ? rankInfoData : rows[index];
					return (
						<div className='artcloud-peoples-row'>
						<div key={index} id={`row-${index + 1}`} className='artcloud-people-member'>
							<input
								type="number"
								value={rowData[0] || ''}
								onChange={(e) => handleChange(index, 0, e.target.value)}
								placeholder={__('Number', 'artcloud-blocks')}
							/>
							<input
								type="text"
								value={rowData[1] || ''}
								onChange={(e) => handleChange(index, 1, e.target.value)}
								placeholder={__('Designation', 'artcloud-blocks')}
							/>
							<select
								value={rowData[2] || ''}
								onChange={(e) => handleChange(index, 2, e.target.value)}
							>
								<option value="">{__('Select People', 'artcloud-blocks')}</option>
								{sortedMembers &&
									sortedMembers.map((post) => (
										<option key={post.id} value={post.id}>
											{post.title.rendered}
										</option>
									))}
							</select>
							<select
								value={rowData[3] || ''}
								onChange={(e) => handleChange(index, 3, e.target.value)}
							>
								<option value="">{__('Select Varalla', 'artcloud-blocks')}</option>
								{sortedMembers &&
									sortedMembers.map((post) => (
										<option key={post.id} value={post.id}>
											{post.title.rendered}
										</option>
									))}
							</select>
						</div>
							<a href="#" className="artcloud-people-delete" onClick={(e) => handleRemoveRow(index)}>
								<span className="dashicons dashicons-trash"></span>
							</a>
						</div>
					);
				})}
				<Button variant="secondary" onClick={handleAddRow} className='artcloud-people-addMember'>
					{__('Add Row', 'artcloud-blocks')}
				</Button>
				<Button variant="primary" type="submit">
					{__('Save', 'artcloud-blocks')}
				</Button>
			</form>
		</>
	);
};
