import { InspectorControls } from "@wordpress/block-editor";
import { __experimentalLinkControl as LinkControl } from "@wordpress/block-editor";
import {
	PanelBody,
	Button,
	TextControl,
	Notice,
	TextareaControl,
} from "@wordpress/components";
import { useState } from "@wordpress/element";

const SidePanel = ({ attributes, setAttributes }) => {
	const { sections } = attributes;
	const [newSectionTitle, setNewSectionTitle] = useState("");
	const [editingSection, setEditingSection] = useState(null);
	const [newLinkTitle, setNewLinkTitle] = useState("");
	const [newLinkUrl, setNewLinkUrl] = useState("");
	const [editingLink, setEditingLink] = useState(null);
	const [editedLinkTitle, setEditedLinkTitle] = useState("");
	const [editedLinkUrl, setEditedLinkUrl] = useState("");
	const [editingSectionTitle, setEditingSectionTitle] = useState(null);
	const [editedSectionTitle, setEditedSectionTitle] = useState("");
	const [editingSvg, setEditingSvg] = useState("");

	const addSection = () => {
		if (!newSectionTitle) return;
		const newSection = {
			id: newSectionTitle.toLowerCase().replace(/\s+/g, "-"),
			title: newSectionTitle,
			links: [],
		};
		setAttributes({
			sections: [...sections, newSection],
		});
		setNewSectionTitle("");
	};

	const removeSection = (index) => {
		const newSections = [...sections];
		newSections.splice(index, 1);
		setAttributes({ sections: newSections });
	};

	const addLink = (sectionIndex) => {
		if (!newLinkTitle || !newLinkUrl) return;
		
		const newSections = [...sections];
		newSections[sectionIndex].links.push({
			id: newLinkTitle.toLowerCase().replace(/\s+/g, "-"),
			title: newLinkTitle,
			url: newLinkUrl,
		});
		setAttributes({ sections: newSections });
		setNewLinkTitle("");
		setNewLinkUrl("");
		setEditingSection(null);
	};

	const removeLink = (sectionIndex, linkIndex) => {
		const newSections = [...sections];
		newSections[sectionIndex].links.splice(linkIndex, 1);
		setAttributes({ sections: newSections });
	};

	const handleDragStart = (e, sectionIndex, linkIndex) => {
		e.dataTransfer.setData('text/plain', JSON.stringify({
			sectionIndex,
			linkIndex
		}));
		e.currentTarget.classList.add('is-dragging');
	};

	const handleDragEnd = (e) => {
		e.currentTarget.classList.remove('is-dragging');
	};

	const handleDrop = (e, targetSectionIndex, targetLinkIndex = null) => {
		e.preventDefault();
		e.stopPropagation();
		e.currentTarget.classList.remove('drag-over');
		
		const data = JSON.parse(e.dataTransfer.getData('text/plain'));
		const { sectionIndex, linkIndex } = data;
		
		if (sectionIndex === targetSectionIndex && linkIndex === targetLinkIndex) {
			return;
		}
		
		const newSections = [...sections];
		const [movedLink] = newSections[sectionIndex].links.splice(linkIndex, 1);
		
		if (targetLinkIndex !== null) {
			newSections[targetSectionIndex].links.splice(targetLinkIndex, 0, movedLink);
		} else {
			newSections[targetSectionIndex].links.push(movedLink);
		}
		
		setAttributes({ sections: newSections });
	};

	const moveSectionUp = (sectionIndex) => {
		if (sectionIndex === 0) return;
		
		const newSections = [...sections];
		const [movedSection] = newSections.splice(sectionIndex, 1);
		newSections.splice(sectionIndex - 1, 0, movedSection);
		setAttributes({ sections: newSections });
	};

	const moveSectionDown = (sectionIndex) => {
		if (sectionIndex === sections.length - 1) return;
		
		const newSections = [...sections];
		const [movedSection] = newSections.splice(sectionIndex, 1);
		newSections.splice(sectionIndex + 1, 0, movedSection);
		setAttributes({ sections: newSections });
	};

	const startEditLink = (sectionIndex, linkIndex) => {
		const link = sections[sectionIndex].links[linkIndex];
		setEditingLink({ sectionIndex, linkIndex });
		setEditedLinkTitle(link.title);
		setEditedLinkUrl(link.url);
	};

	const saveEditedLink = () => {
		if (!editedLinkTitle || !editedLinkUrl || !editingLink) return;
		
		const newSections = [...sections];
		newSections[editingLink.sectionIndex].links[editingLink.linkIndex] = {
			...newSections[editingLink.sectionIndex].links[editingLink.linkIndex],
			id: editedLinkTitle.toLowerCase().replace(/\s+/g, "-"),
			title: editedLinkTitle,
			url: editedLinkUrl,
		};
		setAttributes({ sections: newSections });
		setEditingLink(null);
		setEditedLinkTitle("");
		setEditedLinkUrl("");
	};

	const handleNewUrlChange = (value) => {
		const url = value?.url || value;
		setNewLinkUrl(url);
	};

	const handleEditUrlChange = (value) => {
		const url = value?.url || value;
		setEditedLinkUrl(url);
	};

	const startEditSection = (sectionIndex) => {
		setEditingSectionTitle(sectionIndex);
		setEditedSectionTitle(sections[sectionIndex].title);
		setEditingSvg(sections[sectionIndex].svg || "");
	};

	const saveEditedSection = (sectionIndex) => {
		if (!editedSectionTitle) return;
		
		const newSections = [...sections];
		newSections[sectionIndex] = {
			...newSections[sectionIndex],
			id: editedSectionTitle.toLowerCase().replace(/\s+/g, "-"),
			title: editedSectionTitle,
			svg: editingSvg
		};
		
		setAttributes({ sections: newSections });
		setEditingSectionTitle(null);
		setEditedSectionTitle("");
		setEditingSvg("");
	};

	const validateSvg = (svg) => {
		if (!svg) return true; // SVG vide est valide
		return svg.trim().startsWith('<svg') && svg.trim().endsWith('</svg>');
	};

	return (
		<InspectorControls>
			<PanelBody title="Navigation Sections" initialOpen={true}>
				<div className="section-manager">
					{/* Add new section */}
					<div className="add-section">
						<TextControl
							label="Nouvelle section"
							value={newSectionTitle}
							onChange={setNewSectionTitle}
							placeholder="Titre de la section"
						/>
						<Button
							variant="primary"
							onClick={addSection}
							disabled={!newSectionTitle}
						>
							+ Ajouter une section
						</Button>
					</div>

					{/* Section list */}
					<div className="section-list">
						{sections.map((section, sectionIndex) => (
							<div 
								key={section.id}
								className="section-item"
							>
								<div className="section-header">
									{editingSectionTitle === sectionIndex ? (
										<div className="edit-section">
											<TextControl
												value={editedSectionTitle}
												onChange={setEditedSectionTitle}
												placeholder="Titre de la section"
											/>
											<TextareaControl
												label="SVG Icon (optionnel)"
												value={editingSvg}
												onChange={setEditingSvg}
												placeholder="<svg>...</svg>"
											/>
											{editingSvg && !validateSvg(editingSvg) && (
												<Notice status="error" isDismissible={false}>
													Le code SVG doit commencer par &lt;svg et finir par &lt;/svg&gt;
												</Notice>
											)}
											<div className="edit-actions">
												<Button
													variant="primary"
													onClick={() => saveEditedSection(sectionIndex)}
													disabled={!editedSectionTitle || (editingSvg && !validateSvg(editingSvg))}
												>
													Sauvegarder
												</Button>
												<Button
													variant="secondary"
													onClick={() => {
														setEditingSectionTitle(null);
														setEditedSectionTitle("");
														setEditingSvg("");
													}}
												>
													Annuler
												</Button>
											</div>
										</div>
									) : (
										<>
											<div className="controls-wrapper">
												<div className="section-controls">
													<Button
														icon="arrow-up-alt2"
														onClick={() => moveSectionUp(sectionIndex)}
														disabled={sectionIndex === 0}
														className="move-button"
													/>
													<Button
														icon="arrow-down-alt2"
														onClick={() => moveSectionDown(sectionIndex)}
														disabled={sectionIndex === sections.length - 1}
														className="move-button"
													/>
												</div>
												<div className="section-actions">
													<Button
														variant="secondary"
														icon="edit"
														onClick={() => startEditSection(sectionIndex)}
													/>
													<Button
														variant="tertiary"
														onClick={() => removeSection(sectionIndex)}
													>
														×
													</Button>
												</div>
											</div>
											<h3>
												{section.svg && (
													<span 
														className="section-icon"
														dangerouslySetInnerHTML={{ __html: section.svg }}
													/>
												)}
												{section.title}
											</h3>
										</>
									)}
								</div>

								{/* Links list */}
								<div 
									className="link-list"
									onDragOver={(e) => {
										e.preventDefault();
										e.stopPropagation();
										e.currentTarget.classList.add('drag-over');
									}}
									onDragLeave={(e) => {
										e.currentTarget.classList.remove('drag-over');
									}}
									onDrop={(e) => {
										e.stopPropagation();
										handleDrop(e, sectionIndex);
									}}
								>
									{section.links.map((link, linkIndex) => (
										<div
											key={link.id}
											className="link-item"
											draggable
											onDragStart={(e) => handleDragStart(e, sectionIndex, linkIndex)}
											onDragEnd={handleDragEnd}
											onDragOver={(e) => {
												e.preventDefault();
												e.stopPropagation();
												e.currentTarget.classList.add('drag-over');
											}}
											onDragLeave={(e) => {
												e.currentTarget.classList.remove('drag-over');
											}}
											onDrop={(e) => {
												e.stopPropagation();
												handleDrop(e, sectionIndex, linkIndex);
											}}
										>
											{editingLink?.sectionIndex === sectionIndex && editingLink?.linkIndex === linkIndex ? (
												<div className="edit-link">
													<TextControl
														value={editedLinkTitle}
														onChange={setEditedLinkTitle}
														placeholder="Titre"
													/>
													<LinkControl
														value={{ url: editedLinkUrl }}
														onChange={handleEditUrlChange}
														settings={[]}
													/>
													<div className="edit-actions">
														<Button
															variant="primary"
															onClick={saveEditedLink}
															disabled={!editedLinkTitle || !editedLinkUrl}
														>
															Sauvegarder
														</Button>
														<Button
															variant="secondary"
															onClick={() => {
																setEditingLink(null);
															}}
														>
															Annuler
														</Button>
													</div>
												</div>
											) : (
												<>
													<span className="drag-handle">⋮⋮</span>
													<span className="link-title">{link.title}</span>
													<div className="link-actions">
														<Button
															variant="secondary"
															icon="edit"
															onClick={() => startEditLink(sectionIndex, linkIndex)}
														/>
														<Button
															variant="tertiary"
															onClick={() => removeLink(sectionIndex, linkIndex)}
														>
															×
														</Button>
													</div>
												</>
											)}
										</div>
									))}
								</div>

								{/* Add new link */}
								{editingSection === sectionIndex ? (
									<div className="add-link">
										<TextControl
											label="Titre du lien"
											value={newLinkTitle}
											onChange={setNewLinkTitle}
											placeholder="Titre"
										/>
										<LinkControl
											className="link-control"
											value={{ url: newLinkUrl }}
											onChange={handleNewUrlChange}
											settings={[]}
										/>
										<div className="edit-actions">
											<Button
												variant="primary"
												onClick={() => addLink(sectionIndex)}
												disabled={!newLinkTitle || !newLinkUrl}
											>
												Ajouter
											</Button>
											<Button
												variant="secondary"
												onClick={() => {
													setEditingSection(null);
													setNewLinkTitle("");
													setNewLinkUrl("");
												}}
											>
												Annuler
											</Button>
										</div>
									</div>
								) : (
									<Button
										variant="secondary"
										onClick={() => setEditingSection(sectionIndex)}
									>
										+ Ajouter un lien
									</Button>
								)}
							</div>
						))}
					</div>
				</div>
			</PanelBody>
		</InspectorControls>
	);
};

export default SidePanel;
