import React, { useState, useEffect } from "react";
import { signal } from "@preact/signals-react";
import { useSignals } from "@preact/signals-react/runtime";
import { rest_url, nonce } from "../../App";
import "./search-options.css";

// Signal pour les configurations de recherche
export const post_types = signal([]);
export const selected_taxonomies = signal({});
export const is_url_custom_search = signal(false);
export const url_custom_search = signal("");
export const url_custom_params = signal("");

const SearchOptions = () => {
	// Utiliser useSignals pour que le composant se met à jour quand les signaux changent

	const [postTypes, setPostTypes] = useState([]);
	const [pages, setPages] = useState([]);
	const [loading, setLoading] = useState(false);
	const [selectedType, setSelectedType] = useState("");

	useEffect(() => {
		fetchPostTypes();
		fetchPages();
	}, []);

	const fetchPostTypes = async () => {
		setLoading(true);
		try {
			const response = await fetch(`${rest_url.value}search-bar/post-types`, {
				method: "GET",
				headers: {
					"X-WP-Nonce": nonce.value,
				},
			});
			const data = await response.json();
			if (data.success) {
				setPostTypes(data.post_types);
			}
		} catch (error) {
			console.error("Error fetching post types:", error);
		}
		setLoading(false);
	};

	const fetchPages = async () => {
		try {
			const response = await fetch(`${rest_url.value}search-bar/pages`, {
				method: "GET",
				headers: {
					"X-WP-Nonce": nonce.value,
				},
			});
			const data = await response.json();
			if (data.success) {
				setPages(data.pages);
			}
		} catch (error) {
			console.error("Error fetching pages:", error);
		}
	};

	const handleAddType = () => {
		if (!selectedType) return;

		if (post_types.value.includes(selectedType)) {
			return;
		}

		post_types.value = [...post_types.value, selectedType];

		// Initialiser les taxonomies sélectionnées pour ce type de post
		const newSelectedTaxonomies = { ...selected_taxonomies.value };
		newSelectedTaxonomies[selectedType] = [];
		selected_taxonomies.value = newSelectedTaxonomies;

		setSelectedType("");
		url_custom_params.value = getParamsUrl();
	};

	const handleRemoveType = (typeToRemove) => {
		post_types.value = post_types.value.filter((type) => type !== typeToRemove);

		// Supprimer les taxonomies associées
		const newSelectedTaxonomies = { ...selected_taxonomies.value };
		delete newSelectedTaxonomies[typeToRemove];
		selected_taxonomies.value = newSelectedTaxonomies;
		url_custom_params.value = getParamsUrl();
	};

	const handleTaxonomyChange = (postType, taxonomy, checked) => {
		const currentTaxonomies = selected_taxonomies.value[postType] || [];
		const newTaxonomies = checked
			? [...currentTaxonomies, taxonomy.value]
			: currentTaxonomies.filter((tax) => tax !== taxonomy.value);

		selected_taxonomies.value = {
			...selected_taxonomies.value,
			[postType]: newTaxonomies,
		};
		url_custom_params.value = getParamsUrl();
	};

	const handleCustomUrlChange = (e) => {
		const value = e.target.checked;
		is_url_custom_search.value = value;

		if (!value) {
			url_custom_search.value = "";
			url_custom_params.value = "";
		}
	};

	const handleCustomUrlSelect = (e) => {
		url_custom_search.value = e.target.value;
		url_custom_params.value = getParamsUrl();
	};

	// Filtrer les types déjà ajoutés du dropdown
	const availableTypes = postTypes.filter(
		(type) => !post_types.value.includes(type.value),
	);

	// Fonction pour construire l'URL formatée
	const getParamsUrl = () => {
		if (!url_custom_search.value) return "";

		let selectedPage = pages.find(
			(page) => page.value === url_custom_search.value,
		);
		if (!selectedPage) return "";

		let params = new URLSearchParams();

		// Ajouter les types de posts sélectionnés
		if (post_types.value.length > 0) {
			params.append("cpt", post_types.value.join(","));
		}

		// Ajouter les taxonomies sélectionnées
		Object.entries(selected_taxonomies.value).forEach(
			([postType, taxonomies]) => {
				if (taxonomies.length > 0) {
					params.append(`tax_${postType}`, taxonomies.join(","));
				}
			},
		);

		// Ajouter le paramètre de recherche (placeholder)
		params.append("search_term", "{search_term}");

		return `${selectedPage.value}?${params.toString()}`;
	};

	return (
		<div className="search-options">
			<h2>Configuration de la recherche</h2>

			<div className="option-group">
				<div className="option-group">
					<label>Types de contenu à inclure dans la recherche</label>
					<div className="type-selector">
						<select
							value={selectedType}
							onChange={(e) => setSelectedType(e.target.value)}
							disabled={loading}
						>
							<option value="">Sélectionner un type de contenu</option>
							{availableTypes.map((type) => (
								<option key={type.value} value={type.value}>
									{type.label}
								</option>
							))}
						</select>
						<button
							onClick={handleAddType}
							disabled={!selectedType || loading}
							className="add-type-button"
						>
							Ajouter
						</button>
					</div>

					<div className="selected-types">
						{post_types.value.map((typeValue) => {
							const type = postTypes.find((t) => t.value === typeValue);
							if (!type) return null;

							return (
								<div key={type.value} className="type-container">
									<div className="type-badge">
										<span className="type-label">{type.label}</span>
										<button
											onClick={() => handleRemoveType(type.value)}
											className="remove-type"
											title="Retirer"
										>
											×
										</button>
									</div>

									{type.taxonomies && type.taxonomies.length > 0 && (
										<div className="taxonomies-list">
											<h4 className="taxonomies-title">Taxonomies associées</h4>
											{type.taxonomies.map((taxonomy) => (
												<label
													key={taxonomy.value}
													className="taxonomy-checkbox"
												>
													<input
														type="checkbox"
														checked={
															selected_taxonomies.value[type.value]?.includes(
																taxonomy.value,
															) || false
														}
														onChange={(e) =>
															handleTaxonomyChange(
																type.value,
																taxonomy,
																e.target.checked,
															)
														}
													/>
													{taxonomy.label}
												</label>
											))}
										</div>
									)}
								</div>
							);
						})}
					</div>
				</div>

				<div className="checkbox-group">
					<label className="checkbox-label">
						<input
							type="checkbox"
							checked={is_url_custom_search.value}
							onChange={handleCustomUrlChange}
						/>
						Utiliser une URL personnalisée
					</label>
					{!is_url_custom_search.value && (
						<div className="search-default-info">
							<p className="filter-info">
								La recherche utilisera l'URL WordPress standard :
								/?s=terme_recherché
							</p>
						</div>
					)}
				</div>

				{is_url_custom_search.value && (
					<div className="option-group">
						<label>Page de destination</label>
						<select
							value={url_custom_search.value}
							onChange={handleCustomUrlSelect}
							className="page-select"
						>
							<option value="">Sélectionner une page</option>
							{pages.map((page) => (
								<option key={page.id} value={page.value}>
									{page.label}
								</option>
							))}
						</select>
						{url_custom_search.value && (
							<div className="url-preview">
								<label>Format de l'URL :</label>
								<code className="url-format">{url_custom_params.value}</code>
								<p className="url-info">
									<em>
										Note : {"{search_term}"} sera remplacé par le terme
										recherché
									</em>
								</p>
							</div>
						)}
					</div>
				)}
			</div>
		</div>
	);
};

export default SearchOptions;
