import React, { useState, useEffect } from "react";
import { X, Plus, Trash2, GripVertical, Upload } from "lucide-react";

export default function ProductEditModal({ product, isOpen, onClose, onSave }) {
	const [formData, setFormData] = useState({
		name: "",
		desc: "",
		keywords: "",
		price: "",
		priceReduced: "",
		stock: "",
		images: [],
		specifications: [],
	});

	const [newImages, setNewImages] = useState([]);
	const [draggedIndex, setDraggedIndex] = useState(null);

	useEffect(() => {
		if (product && isOpen) {
			// Parse specifications
			let specs = [];
			if (product.specifications) {
				try {
					specs =
						typeof product.specifications === "string"
							? JSON.parse(product.specifications)
							: product.specifications;
				} catch (e) {
					console.error("Error parsing specifications:", e);
					specs = [];
				}
			}

			// Parse images
			const images = product.images ? product.images.split("|").filter(Boolean) : [];

			setFormData({
				name: product.name || "",
				desc: product.desc || "",
				keywords: product.keywords || "",
				price: product.price || "",
				priceReduced: product.priceReduced || "",
				stock: product.stock || "",
				images: images,
				specifications: specs,
			});
			setNewImages([]);
		}
	}, [product, isOpen]);

	const handleInputChange = (e) => {
		const { name, value } = e.target;
		setFormData((prev) => ({ ...prev, [name]: value }));
	};

	// Specifications handlers
	const addSpecificationGroup = () => {
		setFormData((prev) => ({
			...prev,
			specifications: [...prev.specifications, { "": {} }],
		}));
	};

	const updateSpecificationGroupName = (index, newName) => {
		setFormData((prev) => {
			const updated = [...prev.specifications];
			const oldKey = Object.keys(updated[index])[0];
			const value = updated[index][oldKey];
			updated[index] = { [newName]: value };
			return { ...prev, specifications: updated };
		});
	};

	const addSpecificationItem = (groupIndex) => {
		setFormData((prev) => {
			const updated = [...prev.specifications];
			const groupName = Object.keys(updated[groupIndex])[0];
			updated[groupIndex][groupName][""] = "";
			return { ...prev, specifications: updated };
		});
	};

	const updateSpecificationItem = (groupIndex, oldKey, newKey, value) => {
		setFormData((prev) => {
			const updated = [...prev.specifications];
			const groupName = Object.keys(updated[groupIndex])[0];
			delete updated[groupIndex][groupName][oldKey];
			updated[groupIndex][groupName][newKey] = value;
			return { ...prev, specifications: updated };
		});
	};

	const removeSpecificationItem = (groupIndex, key) => {
		setFormData((prev) => {
			const updated = [...prev.specifications];
			const groupName = Object.keys(updated[groupIndex])[0];
			delete updated[groupIndex][groupName][key];
			return { ...prev, specifications: updated };
		});
	};

	const removeSpecificationGroup = (index) => {
		setFormData((prev) => ({
			...prev,
			specifications: prev.specifications.filter((_, i) => i !== index),
		}));
	};

	// Image handlers
	const handleImageUpload = (e) => {
		const files = Array.from(e.target.files);
		setNewImages((prev) => [...prev, ...files]);
	};

	const removeExistingImage = (index) => {
		setFormData((prev) => ({
			...prev,
			images: prev.images.filter((_, i) => i !== index),
		}));
	};

	const removeNewImage = (index) => {
		setNewImages((prev) => prev.filter((_, i) => i !== index));
	};

	const handleDragStart = (index) => {
		setDraggedIndex(index);
	};

	const handleDragOver = (e, index) => {
		e.preventDefault();
		if (draggedIndex === null || draggedIndex === index) return;

		setFormData((prev) => {
			const updated = [...prev.images];
			const draggedItem = updated[draggedIndex];
			updated.splice(draggedIndex, 1);
			updated.splice(index, 0, draggedItem);
			return { ...prev, images: updated };
		});
		setDraggedIndex(index);
	};

	const handleDragEnd = () => {
		setDraggedIndex(null);
	};

	const handleSubmit = async () => {
		const formDataToSend = new FormData();

		// Add text fields
		formDataToSend.append("id", product.id);
		formDataToSend.append("name", formData.name);
		formDataToSend.append("desc", formData.desc);
		formDataToSend.append("keywords", formData.keywords);
		formDataToSend.append("price", formData.price);
		formDataToSend.append("priceReduced", formData.priceReduced);
		formDataToSend.append("stock", formData.stock);
		formDataToSend.append("existingImages", formData.images.join("|"));
		formDataToSend.append("specifications", JSON.stringify(formData.specifications));

		// Add new image files
		newImages.forEach((file) => {
			formDataToSend.append("images", file);
		});

		await onSave(formDataToSend);
	};

	if (!isOpen) return null;

	return (
		<div
			style={{
				position: "fixed",
				top: 0,
				left: 0,
				right: 0,
				bottom: 0,
				background: "rgba(0,0,0,0.5)",
				zIndex: 9999,
				display: "flex",
				alignItems: "center",
				justifyContent: "center",
				padding: "20px",
			}}>
			<div
				style={{
					background: "white",
					borderRadius: "12px",
					width: "100%",
					maxWidth: "900px",
					maxHeight: "90vh",
					display: "flex",
					flexDirection: "column",
				}}>
				{/* Header */}
				<div
					style={{
						padding: "20px 24px",
						borderBottom: "1px solid #e5e7eb",
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
					}}>
					<h2 style={{ margin: 0, fontSize: "20px", fontWeight: 600 }}>Editează Produs</h2>
					<button
						onClick={onClose}
						style={{
							background: "none",
							border: "none",
							cursor: "pointer",
							padding: "4px",
						}}>
						<X size={24} />
					</button>
				</div>

				{/* Content */}
				<div
					style={{
						padding: "24px",
						overflowY: "auto",
						flex: 1,
					}}>
					{/* Name */}
					<div style={{ marginBottom: "20px" }}>
						<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
							Nume Produs *
						</label>
						<input
							type='text'
							name='name'
							value={formData.name}
							onChange={handleInputChange}
							style={{
								width: "100%",
								padding: "10px 12px",
								border: "1px solid #d1d5db",
								borderRadius: "6px",
								fontSize: "14px",
							}}
						/>
					</div>

					{/* Description */}
					<div style={{ marginBottom: "20px" }}>
						<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
							Descriere
						</label>
						<textarea
							name='desc'
							value={formData.desc}
							onChange={handleInputChange}
							rows={4}
							style={{
								width: "100%",
								padding: "10px 12px",
								border: "1px solid #d1d5db",
								borderRadius: "6px",
								fontSize: "14px",
								resize: "vertical",
							}}
						/>
					</div>

					{/* Keywords */}
					<div style={{ marginBottom: "20px" }}>
						<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
							Cuvinte Cheie
						</label>
						<input
							type='text'
							name='keywords'
							value={formData.keywords}
							onChange={handleInputChange}
							placeholder='Ex: câini, animale, accesorii'
							style={{
								width: "100%",
								padding: "10px 12px",
								border: "1px solid #d1d5db",
								borderRadius: "6px",
								fontSize: "14px",
							}}
						/>
					</div>

					{/* Price Row */}
					<div
						style={{
							display: "grid",
							gridTemplateColumns: "1fr 1fr 1fr",
							gap: "16px",
							marginBottom: "20px",
						}}>
						<div>
							<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
								Preț (RON) *
							</label>
							<input
								type='number'
								name='price'
								value={formData.price}
								onChange={handleInputChange}
								step='0.01'
								style={{
									width: "100%",
									padding: "10px 12px",
									border: "1px solid #d1d5db",
									borderRadius: "6px",
									fontSize: "14px",
								}}
							/>
						</div>
						<div>
							<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
								Preț Redus (RON)
							</label>
							<input
								type='number'
								name='priceReduced'
								value={formData.priceReduced}
								onChange={handleInputChange}
								step='0.01'
								style={{
									width: "100%",
									padding: "10px 12px",
									border: "1px solid #d1d5db",
									borderRadius: "6px",
									fontSize: "14px",
								}}
							/>
						</div>
						<div>
							<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
								Stoc *
							</label>
							<input
								type='number'
								name='stock'
								value={formData.stock}
								onChange={handleInputChange}
								style={{
									width: "100%",
									padding: "10px 12px",
									border: "1px solid #d1d5db",
									borderRadius: "6px",
									fontSize: "14px",
								}}
							/>
						</div>
					</div>

					{/* Images */}
					<div style={{ marginBottom: "20px" }}>
						<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
							Imagini (Drag & Drop pentru a reordona)
						</label>

						<div
							style={{
								display: "grid",
								gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))",
								gap: "12px",
								marginBottom: "12px",
							}}>
							{formData.images.map((img, index) => (
								<div
									key={`existing-${index}`}
									draggable
									onDragStart={() => handleDragStart(index)}
									onDragOver={(e) => handleDragOver(e, index)}
									onDragEnd={handleDragEnd}
									style={{
										position: "relative",
										paddingTop: "100%",
										background: "#f3f4f6",
										borderRadius: "8px",
										cursor: "move",
										border:
											draggedIndex === index
												? "2px solid #3b82f6"
												: "2px solid transparent",
									}}>
									<img
										src={img}
										alt=''
										style={{
											position: "absolute",
											top: 0,
											left: 0,
											width: "100%",
											height: "100%",
											objectFit: "cover",
											borderRadius: "8px",
										}}
									/>
									<button
										onClick={() => removeExistingImage(index)}
										style={{
											position: "absolute",
											top: "4px",
											right: "4px",
											background: "rgba(239, 68, 68, 0.9)",
											color: "white",
											border: "none",
											borderRadius: "4px",
											padding: "4px",
											cursor: "pointer",
										}}>
										<X size={16} />
									</button>
									<div
										style={{
											position: "absolute",
											bottom: "4px",
											left: "4px",
											background: "rgba(0,0,0,0.6)",
											color: "white",
											padding: "2px 6px",
											borderRadius: "4px",
											fontSize: "12px",
										}}>
										<GripVertical size={12} style={{ display: "inline" }} /> {index + 1}
									</div>
								</div>
							))}

							{newImages.map((file, index) => (
								<div
									key={`new-${index}`}
									style={{
										position: "relative",
										paddingTop: "100%",
										background: "#f3f4f6",
										borderRadius: "8px",
										border: "2px dashed #9ca3af",
									}}>
									<img
										src={URL.createObjectURL(file)}
										alt=''
										style={{
											position: "absolute",
											top: 0,
											left: 0,
											width: "100%",
											height: "100%",
											objectFit: "cover",
											borderRadius: "8px",
										}}
									/>
									<button
										onClick={() => removeNewImage(index)}
										style={{
											position: "absolute",
											top: "4px",
											right: "4px",
											background: "rgba(239, 68, 68, 0.9)",
											color: "white",
											border: "none",
											borderRadius: "4px",
											padding: "4px",
											cursor: "pointer",
										}}>
										<X size={16} />
									</button>
									<div
										style={{
											position: "absolute",
											bottom: "4px",
											left: "4px",
											background: "rgba(34, 197, 94, 0.9)",
											color: "white",
											padding: "2px 6px",
											borderRadius: "4px",
											fontSize: "11px",
											fontWeight: 600,
										}}>
										NOU
									</div>
								</div>
							))}
						</div>

						<label
							style={{
								display: "inline-flex",
								alignItems: "center",
								gap: "8px",
								padding: "10px 16px",
								background: "#f3f4f6",
								border: "2px dashed #9ca3af",
								borderRadius: "8px",
								cursor: "pointer",
								fontSize: "14px",
								fontWeight: 500,
							}}>
							<Upload size={18} />
							Adaugă Imagini Noi
							<input
								type='file'
								accept='image/jpeg,image/png,image/webp'
								multiple
								onChange={handleImageUpload}
								style={{ display: "none" }}
							/>
						</label>
					</div>

					{/* Specifications */}
					<div style={{ marginBottom: "20px" }}>
						<div
							style={{
								display: "flex",
								justifyContent: "space-between",
								alignItems: "center",
								marginBottom: "12px",
							}}>
							<label style={{ fontWeight: 500 }}>Specificații</label>
							<button
								onClick={addSpecificationGroup}
								style={{
									display: "flex",
									alignItems: "center",
									gap: "4px",
									padding: "6px 12px",
									background: "#3b82f6",
									color: "white",
									border: "none",
									borderRadius: "6px",
									cursor: "pointer",
									fontSize: "13px",
								}}>
								<Plus size={16} /> Adaugă Grup
							</button>
						</div>

						{formData.specifications.map((group, groupIndex) => {
							const groupName = Object.keys(group)[0];
							const items = group[groupName];

							return (
								<div
									key={groupIndex}
									style={{
										background: "#f9fafb",
										padding: "16px",
										borderRadius: "8px",
										marginBottom: "12px",
									}}>
									<div style={{ display: "flex", gap: "8px", marginBottom: "12px" }}>
										<input
											type='text'
											value={groupName}
											onChange={(e) =>
												updateSpecificationGroupName(groupIndex, e.target.value)
											}
											placeholder='Nume grup (ex: Specificatii)'
											style={{
												flex: 1,
												padding: "8px 12px",
												border: "1px solid #d1d5db",
												borderRadius: "6px",
												fontSize: "14px",
												fontWeight: 500,
											}}
										/>
										<button
											onClick={() => removeSpecificationGroup(groupIndex)}
											style={{
												padding: "8px",
												background: "#ef4444",
												color: "white",
												border: "none",
												borderRadius: "6px",
												cursor: "pointer",
											}}>
											<Trash2 size={16} />
										</button>
									</div>

									{Object.entries(items).map(([key, value], itemIndex) => (
										<div
											key={itemIndex}
											style={{ display: "flex", gap: "8px", marginBottom: "8px" }}>
											<input
												type='text'
												value={key}
												onChange={(e) =>
													updateSpecificationItem(
														groupIndex,
														key,
														e.target.value,
														value
													)
												}
												placeholder='Proprietate (ex: Greutate)'
												style={{
													flex: 1,
													padding: "8px 12px",
													border: "1px solid #d1d5db",
													borderRadius: "6px",
													fontSize: "13px",
												}}
											/>
											<input
												type='text'
												value={value}
												onChange={(e) =>
													updateSpecificationItem(
														groupIndex,
														key,
														key,
														e.target.value
													)
												}
												placeholder='Valoare (ex: 0.01 KG)'
												style={{
													flex: 1,
													padding: "8px 12px",
													border: "1px solid #d1d5db",
													borderRadius: "6px",
													fontSize: "13px",
												}}
											/>
											<button
												onClick={() => removeSpecificationItem(groupIndex, key)}
												style={{
													padding: "8px",
													background: "#f3f4f6",
													border: "1px solid #d1d5db",
													borderRadius: "6px",
													cursor: "pointer",
												}}>
												<X size={16} />
											</button>
										</div>
									))}

									<button
										onClick={() => addSpecificationItem(groupIndex)}
										style={{
											display: "flex",
											alignItems: "center",
											gap: "4px",
											padding: "6px 12px",
											background: "white",
											border: "1px solid #d1d5db",
											borderRadius: "6px",
											cursor: "pointer",
											fontSize: "12px",
											marginTop: "8px",
										}}>
										<Plus size={14} /> Adaugă Item
									</button>
								</div>
							);
						})}
					</div>
				</div>

				{/* Footer */}
				<div
					style={{
						padding: "16px 24px",
						borderTop: "1px solid #e5e7eb",
						display: "flex",
						justifyContent: "flex-end",
						gap: "12px",
					}}>
					<button
						onClick={onClose}
						style={{
							padding: "10px 20px",
							background: "white",
							border: "1px solid #d1d5db",
							borderRadius: "6px",
							cursor: "pointer",
							fontSize: "14px",
							fontWeight: 500,
						}}>
						Anulează
					</button>
					<button
						onClick={handleSubmit}
						style={{
							padding: "10px 20px",
							background: "#3b82f6",
							color: "white",
							border: "none",
							borderRadius: "6px",
							cursor: "pointer",
							fontSize: "14px",
							fontWeight: 500,
						}}>
						Salvează Modificările
					</button>
				</div>
			</div>
		</div>
	);
}
