import React, { useState, useEffect } from "react";
import { useSignals } from "@preact/signals-react/runtime";
import { searchStyles } from "../StyleOptions/style-options";
import {
	post_types,
	selected_taxonomies,
	is_url_custom_search,
	url_custom_search,
	url_custom_params,
} from "../SearchOptions/search-options";
import { home_url } from "../../App";
import "./header.css";
import { nonce, post_id, rest_url, title } from "../../App";
import { signal } from "@preact/signals-react";

// À placer en haut du fichier, en dehors du composant
const STYLE_MAPPING = {
	// Input styles
	inputBgColor: "input_bg",
	inputTextColor: "input_text_color",
	inputPlaceholderColor: "input_placeholder_color",
	inputBorderColor: "input_border_color",
	inputBorderWidth: "input_border_width",
	inputBorderStyle: "input_border_style",
	inputBorderRadius: "input_border_radius",
	inputPadding: "input_padding",
	inputBoxShadow: "input_box_shadow",
	inputTextPlaceHolder: "input_text_place_holder",
	inputNoResultsMessage: "input_no_results_message",

	// Button styles
	buttonPosition: "button_position",
	buttonDisplayType: "button_display_type",
	buttonBgColor: "button_color",
	buttonTextColor: "button_text_color",
	buttonHoverBgColor: "button_hover_color",
	buttonBorderRadiusTopLeft: "button_border_radius_top_left",
	buttonBorderRadiusTopRight: "button_border_radius_top_right",
	buttonBorderRadiusBottomLeft: "button_border_radius_bottom_left",
	buttonBorderRadiusBottomRight: "button_border_radius_bottom_right",
	buttonPaddingTop: "button_padding_top",
	buttonPaddingRight: "button_padding_right",
	buttonPaddingBottom: "button_padding_bottom",
	buttonPaddingLeft: "button_padding_left",
	buttonText: "button_text",
	buttonIcon: "button_icon",

	// Dropdown styles
	dropdownBgColor: "dropdown_bg_color",
	dropdownPadding: "dropdown_padding",
	dropdownBorderColor: "dropdown_border_color",
	dropdownBorderWidth: "dropdown_border_width",
	dropdownBorderStyle: "dropdown_border_style",
	dropdownBorderRadiusTopLeft: "dropdown_border_radius_top_left",
	dropdownBorderRadiusTopRight: "dropdown_border_radius_top_right",
	dropdownBorderRadiusBottomLeft: "dropdown_border_radius_bottom_left",
	dropdownBorderRadiusBottomRight: "dropdown_border_radius_bottom_right",
	dropdownWidth: "dropdown_width",
	dropdownItemPadding: "dropdown_item_padding",
	dropdownItemTextColor: "dropdown_item_text_color",
	dropdownItemHoverBgColor: "dropdown_item_hover_bg_color",
	dropdownItemHoverTextColor: "dropdown_item_hover_text_color",
};

// Créer le mapping inverse une seule fois
const REVERSE_STYLE_MAPPING = Object.entries(STYLE_MAPPING).reduce(
	(acc, [key, value]) => {
		acc[value] = key;
		return acc;
	},
	{},
);

export const search_bar_config_loading = signal(false);
export const search_bar_title = signal("");

const Header = () => {
	const [isSaving, setIsSaving] = useState(false);
	const [message, setMessage] = useState(null);
	const [isLoading, setIsLoading] = useState(!window.page_data.isNewPost);
	const [isEditingTitle, setIsEditingTitle] = useState(false);

	useEffect(() => {
		search_bar_title.value = window.page_data.isNewPost
			? "New Search Bar"
			: title.value;

		if (!window.page_data.isNewPost) {
			search_bar_config_loading.value = true;
			fetchExistingConfig();
		}
	}, []);

	const fetchExistingConfig = async () => {
		try {
			const response = await fetch(
				`${rest_url.value}search-bar/${post_id.value}`,
				{
					method: "GET",
					headers: {
						"X-WP-Nonce": nonce.value,
					},
				},
			);

			const data = await response.json();

			if (data.success && data.config) {
				// Mise à jour des signaux avec les données existantes
				const { style_config, search_config } = data.config;

				// Mise à jour des configurations de recherche
				if (search_config) {
					if (search_config.post_types) {
						post_types.value = search_config.post_types;
					}
					if (search_config.taxonomies) {
						// Conversion du format des taxonomies
						const taxonomiesByPostType = {};
						Object.entries(search_config.taxonomies).forEach(
							([postType, taxonomies]) => {
								if (Array.isArray(taxonomies)) {
									taxonomiesByPostType[postType] = taxonomies;
								}
							},
						);
						selected_taxonomies.value = taxonomiesByPostType;
					}
					if (search_config.is_url_custom_search !== undefined) {
						is_url_custom_search.value = search_config.is_url_custom_search;
					}
					if (search_config.url_custom_search) {
						url_custom_search.value = search_config.url_custom_search;
					}
					if (search_config.url_custom_params) {
						url_custom_params.value = search_config.url_custom_params;
					}
				}

				// Met à jour les signaux avec le mapping inverse
				if (style_config) {
					Object.entries(style_config).forEach(([key, value]) => {
						const signalKey = REVERSE_STYLE_MAPPING[key];
						if (signalKey && searchStyles[signalKey]) {
							searchStyles[signalKey].value = value;
						}
					});
				}
			}
		} catch (error) {
			console.error(error);
			setMessage({
				type: "error",
				text: "Error loading configuration",
			});
		} finally {
			setIsLoading(false);
			search_bar_config_loading.value = false;
		}
	};

	const handleSave = async () => {
		setIsSaving(true);
		setMessage(null);

		try {
			// Convertit les styles pour correspondre à la nouvelle structure
			const style_config = {};
			Object.entries(searchStyles).forEach(([key, signal]) => {
				const configKey = STYLE_MAPPING[key];
				if (configKey) {
					style_config[configKey] = signal.value;
				}
			});

			// Préparation des données de configuration
			const config = {
				title: search_bar_title.value,
				search_config: {
					post_types: post_types.value,
					taxonomies: selected_taxonomies.value,
					is_url_custom_search: is_url_custom_search.value,
					url_custom_search: url_custom_search.value,
					url_custom_params: url_custom_params.value,
					home_url: home_url.value,
					custom_fields: [],
					weights: {
						title: 10,
						content: 5,
						excerpt: 7,
					},
				},
				display_config: {},
				style_config,
			};

			console.log("Saving configuration:", config);

			const response = await fetch(
				`${window.page_data.restUrl}search-bar/${window.page_data.postId}`,
				{
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						"X-WP-Nonce": window.page_data.nonce,
					},
					body: JSON.stringify({ config }),
				},
			);

			const data = await response.json();

			if (data.success) {
				setMessage({
					type: "success",
					text: window.page_data.isNewPost
						? "Search bar created!"
						: "Changes saved successfully!",
				});
				if (window.page_data.isNewPost) {
					window.location.href = `${home_url.value}/wp-admin/post.php?post=${data.post_id}&action=edit`;
				}
			} else {
				setMessage({
					type: "error",
					text: data.message || "An error occurred",
				});
			}
		} catch (error) {
			setMessage({ type: "error", text: "Connection error" });
		} finally {
			setIsSaving(false);
		}
	};

	const handleTitleClick = () => {
		if (!isLoading) {
			setIsEditingTitle(true);
		}
	};

	const handleTitleChange = (e) => {
		search_bar_title.value = e.target.value;
		title.value = e.target.value;
	};

	const handleTitleBlur = () => {
		setIsEditingTitle(false);
	};

	const handleTitleKeyDown = (e) => {
		if (e.key === "Enter") {
			setIsEditingTitle(false);
		}
	};

	return (
		<div className="search-builder-header">
			<div className="header-content">
				<div className="header-title">
					{isEditingTitle ? (
						<input
							type="text"
							value={search_bar_title.value}
							onChange={handleTitleChange}
							onBlur={handleTitleBlur}
							onKeyDown={handleTitleKeyDown}
							className="title-input"
							autoFocus
						/>
					) : (
						<h1 onClick={handleTitleClick} className="title-text">
							{search_bar_title.value}
							<span className="edit-icon">✎</span>
						</h1>
					)}
					<p className="header-status">
						{isLoading
							? "Loading..."
							: window.page_data.isNewPost
							? "Create a new custom search bar"
							: `Status: ${
									window.page_data.postStatus === "publish"
										? "Published"
										: "Draft"
							  }`}
					</p>
				</div>

				<div className="header-actions">
					{message && (
						<span className={`save-message ${message.type}`}>
							{message.text}
						</span>
					)}
					<button
						className="save-button"
						onClick={handleSave}
						disabled={isSaving || isLoading}
					>
						{isLoading
							? "Loading..."
							: isSaving
							? "Saving..."
							: window.page_data.isNewPost
							? "Create"
							: "Update"}
					</button>
				</div>
			</div>
		</div>
	);
};

export default Header;
