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

export default function ProductAddModal({ isOpen, onClose, onSave, categories }) {
	const [formData, setFormData] = useState({
		name: "",
		desc: "",
		keywords: "",
		price: "",
		priceReduced: "",
		stock: "",
		categoryName: "",
		categorySlug: "",
		subcategoryName: "",
		subcategorySlug: "",
		thirdCategoryName: "",
		thirdCategorySlug: "",
		specifications: [],
	});

	const [newImages, setNewImages] = useState([]);
	const [selectedCategory, setSelectedCategory] = useState(null);
	const [selectedSubcategory, setSelectedSubcategory] = useState(null);
	const [availableSubcategories, setAvailableSubcategories] = useState([]);
	const [availableThirdCategories, setAvailableThirdCategories] = useState([]);

	useEffect(() => {
		if (!isOpen) {
			// Reset form when modal closes
			setFormData({
				name: "",
				desc: "",
				keywords: "",
				price: "",
				priceReduced: "",
				stock: "",
				categoryName: "",
				categorySlug: "",
				subcategoryName: "",
				subcategorySlug: "",
				thirdCategoryName: "",
				thirdCategorySlug: "",
				specifications: [],
			});
			setNewImages([]);
			setSelectedCategory(null);
			setSelectedSubcategory(null);
			setAvailableSubcategories([]);
			setAvailableThirdCategories([]);
		}
	}, [isOpen]);

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

	// Category handlers
	const handleCategoryChange = (e) => {
		const category = categories.find((c) => c.slug === e.target.value);
		if (category) {
			setSelectedCategory(category);
			setFormData((prev) => ({
				...prev,
				categoryName: category.name,
				categorySlug: category.slug,
				subcategoryName: "",
				subcategorySlug: "",
				thirdCategoryName: "",
				thirdCategorySlug: "",
			}));
			setAvailableSubcategories(category.subcategories || []);
			setAvailableThirdCategories([]);
			setSelectedSubcategory(null);
		}
	};

	const handleSubcategoryChange = (e) => {
		const subcategory = availableSubcategories.find((s) => s.slug === e.target.value);
		if (subcategory) {
			setSelectedSubcategory(subcategory);
			setFormData((prev) => ({
				...prev,
				subcategoryName: subcategory.name,
				subcategorySlug: subcategory.slug,
				thirdCategoryName: "",
				thirdCategorySlug: "",
			}));
			setAvailableThirdCategories(subcategory.thirdCategories || []);
		}
	};

	const handleThirdCategoryChange = (e) => {
		const thirdCategory = availableThirdCategories.find((t) => t.slug === e.target.value);
		if (thirdCategory) {
			setFormData((prev) => ({
				...prev,
				thirdCategoryName: thirdCategory.name,
				thirdCategorySlug: thirdCategory.slug,
			}));
		}
	};

	// 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 removeNewImage = (index) => {
		setNewImages((prev) => prev.filter((_, i) => i !== index));
	};

	const handleSubmit = async () => {
		// Validation
		if (!formData.name || !formData.price || !formData.stock) {
			alert("Completați câmpurile obligatorii: Nume, Preț, Stoc");
			return;
		}
		if (!formData.categorySlug) {
			alert("Selectați o categorie");
			return;
		}
		if (newImages.length === 0) {
			alert("Adăugați cel puțin o imagine");
			return;
		}

		const formDataToSend = new FormData();

		// Add text fields
		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("categoryName", formData.categoryName);
		formDataToSend.append("categorySlug", formData.categorySlug);
		formDataToSend.append("subcategoryName", formData.subcategoryName);
		formDataToSend.append("subcategorySlug", formData.subcategorySlug);
		formDataToSend.append("thirdCategoryName", formData.thirdCategoryName);
		formDataToSend.append("thirdCategorySlug", formData.thirdCategorySlug);
		formDataToSend.append("specifications", JSON.stringify(formData.specifications));

		// Add 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 }}>Adaugă Produs Nou</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>

					{/* Categories */}
					<div style={{ marginBottom: "20px" }}>
						<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
							Categorie *
						</label>
						<select
							value={formData.categorySlug}
							onChange={handleCategoryChange}
							style={{
								width: "100%",
								padding: "10px 12px",
								border: "1px solid #d1d5db",
								borderRadius: "6px",
								fontSize: "14px",
							}}>
							<option value=''>Selectează categoria</option>
							{categories.map((cat) => (
								<option key={cat.slug} value={cat.slug}>
									{cat.name}
								</option>
							))}
						</select>
					</div>

					{availableSubcategories.length > 0 && (
						<div style={{ marginBottom: "20px" }}>
							<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
								Subcategorie
							</label>
							<select
								value={formData.subcategorySlug}
								onChange={handleSubcategoryChange}
								style={{
									width: "100%",
									padding: "10px 12px",
									border: "1px solid #d1d5db",
									borderRadius: "6px",
									fontSize: "14px",
								}}>
								<option value=''>Selectează subcategoria</option>
								{availableSubcategories.map((sub) => (
									<option key={sub.slug} value={sub.slug}>
										{sub.name}
									</option>
								))}
							</select>
						</div>
					)}

					{availableThirdCategories.length > 0 && (
						<div style={{ marginBottom: "20px" }}>
							<label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
								Subcategorie Nivel 3
							</label>
							<select
								value={formData.thirdCategorySlug}
								onChange={handleThirdCategoryChange}
								style={{
									width: "100%",
									padding: "10px 12px",
									border: "1px solid #d1d5db",
									borderRadius: "6px",
									fontSize: "14px",
								}}>
								<option value=''>Selectează subcategoria nivel 3</option>
								{availableThirdCategories.map((third) => (
									<option key={third.slug} value={third.slug}>
										{third.name}
									</option>
								))}
							</select>
						</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 * (minim 1)
						</label>

						<div
							style={{
								display: "grid",
								gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))",
								gap: "12px",
								marginBottom: "12px",
							}}>
							{newImages.map((file, index) => (
								<div
									key={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>
							))}
						</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
							<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: "#10b981",
							color: "white",
							border: "none",
							borderRadius: "6px",
							cursor: "pointer",
							fontSize: "14px",
							fontWeight: 500,
						}}>
						Adaugă Produs
					</button>
				</div>
			</div>
		</div>
	);
}
