"use client";

import AdminLayout from "@/components/admin/layout";
import { useState, useEffect, useRef } from "react";
import { Save, ArrowLeft, Loader, Trash2, Plus, X, Edit2, Image as ImageIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";

export default function EditProductPage({ params }) {
	const router = useRouter();
	const { id } = params;
	const editorRef = useRef(null);

	const [loading, setLoading] = useState(true);
	const [saving, setSaving] = useState(false);
	const [formData, setFormData] = useState({
		name: "",
		desc: "",
		keywords: "",
		price: "",
		priceReduced: "",
		stock: "",
		categoryName: "",
		categorySlug: "",
		subcategoryName: "",
		subcategorySlug: "",
		thirdCategoryName: "",
		thirdCategorySlug: "",
		url: "",
		supplier: "",
		sku: "",
		ean: "",
		is_variable: false,
		listedBy: null,
	});
	const [listedByUser, setListedByUser] = useState([]);

	const [images, setImages] = useState([]);
	const [specifications, setSpecifications] = useState([]);
	const [variations, setVariations] = useState([]);
	const [newImageUrl, setNewImageUrl] = useState("");
	const [editingSpec, setEditingSpec] = useState(null);
	const [newSpec, setNewSpec] = useState({ key: "", value: "" });

	const [verified, setVerified] = useState(0);
	const [rejectReason, setRejectReason] = useState("");

	useEffect(() => {
		if (id) {
			loadProduct();
		}
	}, [id]);

	async function loadProduct() {
		try {
			setLoading(true);
			const response = await fetchWrapper.get(`/api/admin/products/${id}`);

			if (response.product) {
				const product = response.product;
				setFormData({
                         id: product.id || "nedefinit", 
					name: product.name || "",
					desc: product.desc || "",
					keywords: product.keywords || "",
					price: product.price || "",
					priceReduced: product.priceReduced || "",
					stock: product.stock || "",
					categoryName: product.categoryName || "",
					categorySlug: product.categorySlug || "",
					subcategoryName: product.subcategoryName || "",
					subcategorySlug: product.subcategorySlug || "",
					thirdCategoryName: product.thirdCategoryName || "",
					thirdCategorySlug: product.thirdCategorySlug || "",
					url: product.url || "",
					supplier: product.supplier || "",
					sku: product.sku || "",
					ean: product.ean || "",
					is_variable: product.is_variable || false,
					listedBy: product.listedBy,
					verified: product.verified || 0,
				});

                    setVerified(product.verified || 0); 

				// Parse images
				if (product.images) {
					try {
						// Imaginile sunt salvate ca string cu separator |
						const imageList = product.images.includes("|")
							? product.images
									.split("|")
									.map((i) => i.trim())
									.filter((i) => i)
							: product.images
									.split(",")
									.map((i) => i.trim())
									.filter((i) => i);
						setImages(imageList);
					} catch (error) {
						console.error("Error parsing images:", error);
						setImages([]);
					}
				}

				// Parse specifications
				if (product.specifications) {
					try {
						const specs =
							typeof product.specifications === "string"
								? JSON.parse(product.specifications)
								: product.specifications;

						if (specs) {
							const specsArray = Object.entries(specs[0].Specificatii).map(([key, value]) => ({
								key,
								value: typeof value === "object" ? JSON.stringify(value) : String(value),
							}));

							setSpecifications(specsArray);
						} else {
							setSpecifications([]);
						}
					} catch (error) {
						console.error("Error parsing specifications:", error);
						setSpecifications([]);
					}
				}

				// Parse variations
				if (product.variations) {
					try {
						const vars =
							typeof product.variations === "string"
								? JSON.parse(product.variations)
								: product.variations;
						setVariations(Array.isArray(vars) ? vars : []);
					} catch {
						setVariations([]);
					}
				}

				// Set HTML content in editor
				if (editorRef.current && product.desc) {
					editorRef.current.innerHTML = product.desc;
				}

				if (product.listedBy != 0) {
					const resp = await fetchWrapper.get("/api/admin/users/" + product.listedBy);
					setListedByUser(resp[0].userData);
					console.log(resp[0].userData);
				}
			}
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: "Nu s-a putut încărca produsul",
				confirmButtonColor: "#dc3545",
			});
			console.error("Eroare la încărcarea produsului:", error);
			router.push("/admin/produse");
		} finally {
			setLoading(false);
		}
	}

	const saveStatus = async (e, productId) => {
          e.preventDefault(); 
		try {
			await fetchWrapper.post("/api/admin/products/updatestats", {
				productId: productId,
				verified,
				rejectReason: verified === 2 ? rejectReason : "",
			});
			alert("Status actualizat!");
               loadProduct(); 
		} catch (err) {
			console.error(err);
			alert("Eroare la salvare!");
		}
	};

	const handleChange = (e) => {
		const { name, value, type, checked } = e.target;
		setFormData((prev) => ({
			...prev,
			[name]: type === "checkbox" ? checked : value,
		}));
	};

	// Editor HTML functions
	const execCommand = (command, value = null) => {
		document.execCommand(command, false, value);
		editorRef.current.focus();
	};

	// Image management
	const addImage = () => {
		if (newImageUrl.trim()) {
			setImages([...images, newImageUrl.trim()]);
			setNewImageUrl("");
		}
	};

	const removeImage = (index) => {
		setImages(images.filter((_, i) => i !== index));
	};

	// Specifications management
	const addSpecification = () => {
		if (newSpec.key.trim() && newSpec.value.trim()) {
			setSpecifications([...specifications, { key: newSpec.key.trim(), value: newSpec.value.trim() }]);
			setNewSpec({ key: "", value: "" });
		}
	};

	const updateSpecification = (index, field, value) => {
		const updated = [...specifications];
		updated[index][field] = value;
		setSpecifications(updated);
	};

	const removeSpecification = (index) => {
		setSpecifications(specifications.filter((_, i) => i !== index));
	};

	const startEditSpec = (index) => {
		setEditingSpec(index);
	};

	const stopEditSpec = () => {
		setEditingSpec(null);
	};

	const handleSubmit = async (e) => {
		e.preventDefault();

		// Validare
		if (!formData.name || !formData.price || !formData.sku) {
			Swal.fire({
				icon: "warning",
				title: "Atenție",
				text: "Completează toate câmpurile obligatorii (Nume, Preț, SKU)",
				confirmButtonColor: "#ffc107",
			});
			return;
		}

		const result = await Swal.fire({
			title: "Salvezi modificările?",
			text: "Produsul va fi actualizat în baza de date",
			icon: "question",
			showCancelButton: true,
			confirmButtonColor: "#198754",
			cancelButtonColor: "#6c757d",
			confirmButtonText: "Da, salvează!",
			cancelButtonText: "Anulează",
		});

		if (result.isConfirmed) {
			try {
				setSaving(true);

				Swal.fire({
					title: "Se salvează...",
					allowOutsideClick: false,
					didOpen: () => {
						Swal.showLoading();
					},
				});

				// Get HTML content from editor
				const descContent = editorRef.current ? editorRef.current.innerHTML : "";

				// Convert specifications array to object
				const specsObject = { Specificatii: {} };

				specifications.forEach((spec) => {
					if (spec.key && spec.key.trim()) {
						specsObject.Specificatii[spec.key] = spec.value || "";
					}
				});

				const result = [specsObject];

				// Pregătește datele pentru trimitere
				const dataToSend = {
					name: formData.name,
					desc: descContent || null,
					keywords: formData.keywords || null,
					price: parseFloat(formData.price),
					priceReduced: formData.priceReduced ? parseFloat(formData.priceReduced) : null,
					stock: formData.stock ? parseInt(formData.stock) : 0,
					categoryName: formData.categoryName || "",
					categorySlug: formData.categorySlug || "",
					subcategoryName: formData.subcategoryName || null,
					subcategorySlug: formData.subcategorySlug || null,
					thirdCategoryName: formData.thirdCategoryName || null,
					thirdCategorySlug: formData.thirdCategorySlug || null,
					url: formData.url || "",
					supplier: formData.supplier || "",
					sku: formData.sku,
					ean: formData.ean || "",
					images: images,
					is_variable: formData.is_variable ? 1 : 0,
					variations: variations.length > 0 ? JSON.stringify(variations) : null,
					specifications: result,
				};

				await fetchWrapper.put(`/api/admin/products/${id}`, dataToSend);

				await Swal.fire({
					icon: "success",
					title: "Salvat!",
					text: "Produsul a fost actualizat cu succes.",
					timer: 2000,
					showConfirmButton: false,
				});

				router.push("/admin/produse");
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare",
					text: error.message || "Nu s-a putut salva produsul",
					confirmButtonColor: "#dc3545",
				});
				console.error("Eroare la salvarea produsului:", error);
			} finally {
				setSaving(false);
			}
		}
	};

	const handleDelete = async () => {
		const result = await Swal.fire({
			title: "Ești sigur?",
			html: `Vrei să ștergi produsul <strong>${formData.name}</strong>?<br><small>Această acțiune nu poate fi anulată!</small>`,
			icon: "warning",
			showCancelButton: true,
			confirmButtonColor: "#dc3545",
			cancelButtonColor: "#6c757d",
			confirmButtonText: "Da, șterge!",
			cancelButtonText: "Anulează",
		});

		if (result.isConfirmed) {
			try {
				Swal.fire({
					title: "Se șterge...",
					allowOutsideClick: false,
					didOpen: () => {
						Swal.showLoading();
					},
				});

				await fetchWrapper.delete(`/api/admin/products/${id}`);

				await Swal.fire({
					icon: "success",
					title: "Șters!",
					text: "Produsul a fost șters cu succes.",
					timer: 2000,
					showConfirmButton: false,
				});

				router.push("/admin/produse");
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare",
					text: "Nu s-a putut șterge produsul",
					confirmButtonColor: "#dc3545",
				});
				console.error("Eroare la ștergerea produsului:", error);
			}
		}
	};

	if (loading) {
		return (
			<AdminLayout>
				<div style={{ textAlign: "center", padding: "5rem" }}>
					<div
						className='spinner-border text-primary'
						role='status'
						style={{ width: "3rem", height: "3rem" }}>
						<span className='visually-hidden'>Se încarcă...</span>
					</div>
					<p style={{ marginTop: "1rem", color: "var(--text-secondary)" }}>Se încarcă produsul...</p>
				</div>
			</AdminLayout>
		);
	}

	return (
		<AdminLayout>
			<div className='page-header'>
				<div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "1rem" }}>
					<Link href='/admin/produse' className='btn btn-outline-secondary'>
						<ArrowLeft size={18} />
					</Link>
					<div>
						<h1 className='page-title' style={{ marginBottom: "0" }}>
							Editează Produs
						</h1>
						<p className='page-description'>ID: #{id}</p>
					</div>
				</div>
			</div>

			<form onSubmit={handleSubmit}>
				<div className='row'>
					<div className='col-lg-8'>
						<div className='content-card'>
							<h3 className='card-title'>Informații Generale</h3>
							{formData.listedBy && (
								<div
									className='card shadow-sm border-0'
									style={{ maxWidth: "600px", margin: "0 auto", borderRadius: "16px" }}>
									Aceste date sunt afisate pentru ca produsul este listat pentru zona de
									marketplace.
									<br />
									<br />
									<div className='card-body d-flex align-items-center gap-3'>
										<img
											src={listedByUser.marketplace_avatar}
											alt='avatar'
											className='rounded-circle'
											style={{ width: "70px", height: "70px", objectFit: "cover" }}
										/>
										<div>
											<h5 className='card-title mb-1'>
												{listedByUser.firstName} {listedByUser.lastName}
											</h5>
											<p className='text-muted mb-0'>{listedByUser.email}</p>
										</div>
									</div>
									<hr className='my-0' />
									<div
										className='card-body bg-light'
										style={{ borderRadius: "0 0 16px 16px" }}>
										<div
											className='p-3 mb-3 bg-white border rounded'
											style={{ borderRadius: "12px" }}>
											<p className='mb-1'>
												<strong>ID:</strong> {listedByUser.id}
											</p>
											<p className='mb-0'>
												<strong>Marketplace:</strong>{" "}
												{listedByUser.marketplace ? "Activ" : "Inactiv"}
											</p>
										</div>

										<div
											className='p-3 mb-3 bg-white border rounded'
											style={{ borderRadius: "12px" }}>
											<h6 className='fw-bold mb-2'>Detalii firmă</h6>
											<p className='mb-1'>
												<strong>Nume firmă:</strong> {listedByUser.nume_firma}
											</p>
											<p className='mb-1'>
												<strong>CUI:</strong> {listedByUser.cui_firma}
											</p>
											<p className='mb-1'>
												<strong>Nr. Înregistrare:</strong>{" "}
												{listedByUser.nr_inregistrare_firma}
											</p>
											<p className='mb-0'>
												<strong>Adresă:</strong> {listedByUser.adresa_firma}
											</p>
										</div>

										<div
											className='p-3 bg-white border rounded'
											style={{ borderRadius: "12px" }}>
											<p className='mb-1'>
												<strong>Telefon:</strong>{" "}
												{listedByUser.phone || "Nespecificat"}
											</p>
											<p className='mb-1'>
												<strong>Creat la:</strong>{" "}
												{new Date(listedByUser.createdAt).toLocaleString()}
											</p>
											<p className='mb-0'>
												<strong>Ultima actualizare:</strong>{" "}
												{new Date(listedByUser.updatedAt).toLocaleString()}
											</p>
											<p className='mb-0'>
												<strong>Status listare produs:</strong>{" "}
												{formData.verified === 2 ? (
													<>
														<span style={{ color: "red" }}>RESPINS</span>
													</>
												) : formData.verified === 1 ? (
													<>
														<span style={{ color: "green" }}>APROBAT</span>
													</>
												) : (
													<>
														<span style={{ color: "orange" }}>
															ÎN AȘTEPTARE
														</span>
													</>
												)}
											</p>

											<div
												className='mt-3 p-3 border rounded bg-light'
												style={{ maxWidth: "400px" }}>
												<label className='form-label fw-bold'>Status produs:</label>

												<select
													className='form-select form-select-sm'
													value={verified}
													onChange={(e) =>
														setVerified(parseInt(e.target.value))
													}>
													<option value={0}>IN VERIFICARE</option>
													<option value={1}>VERIFICAT</option>
													<option value={2}>RESPINS</option>
												</select>

												{verified === 2 && (
													<div className='mt-2'>
														<label className='form-label'>
															Motiv respingere
														</label>
														<input
															type='text'
															className='form-control form-control-sm'
															placeholder='Introduceți motivul...'
															value={rejectReason}
															onChange={(e) =>
																setRejectReason(e.target.value)
															}
														/>
													</div>
												)}

												<button
													className='btn btn-primary btn-sm mt-3'
													onClick={(e) => saveStatus(e, formData.id)}>
													Salvează
												</button>
											</div>
										</div>
									</div>
								</div>
							)}
							<div className='mb-3'>
								<label className='form-label'>
									Nume Produs <span style={{ color: "#dc3545" }}>*</span>
								</label>
								<input
									type='text'
									className='form-control'
									name='name'
									value={formData.name}
									onChange={handleChange}
									required
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>URL (Slug)</label>
								<input
									type='text'
									className='form-control'
									name='url'
									value={formData.url}
									onChange={handleChange}
								/>
							</div>

							<div className='row'>
								<div className='col-md-6 mb-3'>
									<label className='form-label'>
										SKU <span style={{ color: "#dc3545" }}>*</span>
									</label>
									<input
										type='text'
										className='form-control'
										name='sku'
										value={formData.sku}
										onChange={handleChange}
										required
									/>
								</div>
								<div className='col-md-6 mb-3'>
									<label className='form-label'>EAN</label>
									<input
										type='text'
										className='form-control'
										name='ean'
										value={formData.ean}
										onChange={handleChange}
									/>
								</div>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Furnizor</label>
								<input
									type='text'
									className='form-control'
									name='supplier'
									value={formData.supplier}
									onChange={handleChange}
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Descriere Completă</label>

								{/* HTML Editor Toolbar */}
								<div className='btn-toolbar mb-2' style={{ gap: "0.25rem", flexWrap: "wrap" }}>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("bold")}
										title='Bold'>
										<strong>B</strong>
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("italic")}
										title='Italic'>
										<em>I</em>
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("underline")}
										title='Underline'>
										<u>U</u>
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("insertUnorderedList")}
										title='Lista'>
										• Lista
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("insertOrderedList")}
										title='Lista Numerotată'>
										1. Lista
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("formatBlock", "h3")}
										title='Titlu'>
										H3
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => execCommand("formatBlock", "p")}
										title='Paragraf'>
										P
									</button>
									<button
										type='button'
										className='btn btn-sm btn-outline-secondary'
										onClick={() => {
											const url = prompt("Introdu URL-ul:");
											if (url) execCommand("createLink", url);
										}}
										title='Link'>
										🔗 Link
									</button>
								</div>

								<div
									ref={editorRef}
									contentEditable
									className='form-control'
									style={{
										minHeight: "300px",
										maxHeight: "500px",
										overflowY: "auto",
										padding: "1rem",
									}}
								/>
								<small className='form-text text-muted'>
									Folosește toolbar-ul pentru formatare text
								</small>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Cuvinte Cheie (SEO)</label>
								<input
									type='text'
									className='form-control'
									name='keywords'
									value={formData.keywords}
									onChange={handleChange}
									placeholder='laptop, dell, xps'
								/>
							</div>
						</div>

						{/* Imagini Section */}
						<div className='content-card'>
							<h3 className='card-title'>Imagini Produs</h3>

							{images.length > 0 && (
								<div
									style={{
										display: "grid",
										gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))",
										gap: "1rem",
										marginBottom: "1.5rem",
									}}>
									{images.map((img, index) => (
										<div
											key={index}
											style={{
												position: "relative",
												border: "1px solid var(--border-color)",
												borderRadius: "0.5rem",
												overflow: "hidden",
											}}>
											<img
												src={img}
												alt={`Product ${index + 1}`}
												style={{
													width: "100%",
													height: "150px",
													objectFit: "cover",
												}}
											/>
											<button
												type='button'
												className='btn btn-danger btn-sm'
												onClick={() => removeImage(index)}
												style={{
													position: "absolute",
													top: "0.5rem",
													right: "0.5rem",
												}}>
												<X size={14} />
											</button>
										</div>
									))}
								</div>
							)}

							<div className='input-group'>
								<input
									type='text'
									className='form-control'
									placeholder='URL imagine'
									value={newImageUrl}
									onChange={(e) => setNewImageUrl(e.target.value)}
									onKeyPress={(e) => e.key === "Enter" && (e.preventDefault(), addImage())}
								/>
								<button type='button' className='btn btn-primary' onClick={addImage}>
									<Plus size={18} /> Adaugă Imagine
								</button>
							</div>
							<small className='form-text text-muted'>
								Adaugă URL-ul imaginii și apasă Enter sau butonul
							</small>
						</div>

						{/* Specifications Section */}
						<div className='content-card'>
							<h3 className='card-title'>Specificații Tehnice</h3>

							{specifications.length > 0 && (
								<div style={{ marginBottom: "1.5rem" }}>
									{specifications.map((spec, index) => (
										<div
											key={index}
											className='d-flex align-items-center gap-2 mb-2'
											style={{
												padding: "0.75rem",
												backgroundColor: "var(--main-bg)",
												borderRadius: "0.5rem",
											}}>
											{editingSpec === index ? (
												<>
													<input
														type='text'
														className='form-control form-control-sm'
														value={spec.key || ""}
														onChange={(e) =>
															updateSpecification(
																index,
																"key",
																e.target.value
															)
														}
														placeholder='Nume specificație'
													/>
													<input
														type='text'
														className='form-control form-control-sm'
														value={spec.value || ""}
														onChange={(e) =>
															updateSpecification(
																index,
																"value",
																e.target.value
															)
														}
														placeholder='Valoare'
													/>
													<button
														type='button'
														className='btn btn-sm btn-success'
														onClick={stopEditSpec}>
														<Save size={14} />
													</button>
												</>
											) : (
												<>
													<div style={{ flex: 1 }}>
														<strong>{spec.key || "N/A"}:</strong>{" "}
														{String(spec.value || "")}
													</div>
													<button
														type='button'
														className='btn btn-sm btn-outline-secondary'
														onClick={() => startEditSpec(index)}>
														<Edit2 size={14} />
													</button>
													<button
														type='button'
														className='btn btn-sm btn-danger'
														onClick={() => removeSpecification(index)}>
														<Trash2 size={14} />
													</button>
												</>
											)}
										</div>
									))}
								</div>
							)}

							<div className='row g-2'>
								<div className='col-md-5'>
									<input
										type='text'
										className='form-control'
										placeholder='Nume specificație (ex: Display)'
										value={newSpec.key}
										onChange={(e) => setNewSpec({ ...newSpec, key: e.target.value })}
									/>
								</div>
								<div className='col-md-5'>
									<input
										type='text'
										className='form-control'
										placeholder='Valoare (ex: 15.6 inch)'
										value={newSpec.value}
										onChange={(e) => setNewSpec({ ...newSpec, value: e.target.value })}
										onKeyPress={(e) =>
											e.key === "Enter" && (e.preventDefault(), addSpecification())
										}
									/>
								</div>
								<div className='col-md-2'>
									<button
										type='button'
										className='btn btn-primary w-100'
										onClick={addSpecification}>
										<Plus size={18} />
									</button>
								</div>
							</div>
						</div>
					</div>

					<div className='col-lg-4'>
						<div className='content-card'>
							<h3 className='card-title'>Categorie</h3>

							<div className='mb-3'>
								<label className='form-label'>Categorie Principală</label>
								<input
									type='text'
									className='form-control'
									name='categoryName'
									value={formData.categoryName}
									onChange={handleChange}
									placeholder='Laptopuri'
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Slug Categorie</label>
								<input
									type='text'
									className='form-control'
									name='categorySlug'
									value={formData.categorySlug}
									onChange={handleChange}
									placeholder='laptopuri'
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Subcategorie</label>
								<input
									type='text'
									className='form-control'
									name='subcategoryName'
									value={formData.subcategoryName}
									onChange={handleChange}
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Slug Subcategorie</label>
								<input
									type='text'
									className='form-control'
									name='subcategorySlug'
									value={formData.subcategorySlug}
									onChange={handleChange}
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Categorie Terțiară</label>
								<input
									type='text'
									className='form-control'
									name='thirdCategoryName'
									value={formData.thirdCategoryName}
									onChange={handleChange}
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Slug Categorie Terțiară</label>
								<input
									type='text'
									className='form-control'
									name='thirdCategorySlug'
									value={formData.thirdCategorySlug}
									onChange={handleChange}
								/>
							</div>
						</div>

						<div className='content-card'>
							<h3 className='card-title'>Preț și Stoc</h3>

							<div className='mb-3'>
								<label className='form-label'>
									Preț (RON) <span style={{ color: "#dc3545" }}>*</span>
								</label>
								<input
									type='number'
									step='0.01'
									className='form-control'
									name='price'
									value={formData.price}
									onChange={handleChange}
									required
								/>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Preț Redus (RON)</label>
								<input
									type='number'
									step='0.01'
									className='form-control'
									name='priceReduced'
									value={formData.priceReduced}
									onChange={handleChange}
								/>
								<small className='form-text text-muted'>
									Lasă gol dacă produsul nu este la reducere
								</small>
							</div>

							<div className='mb-3'>
								<label className='form-label'>Stoc Disponibil</label>
								<input
									type='number'
									className='form-control'
									name='stock'
									value={formData.stock}
									onChange={handleChange}
								/>
							</div>
						</div>

						<div className='d-grid gap-2'>
							<button type='submit' className='btn btn-success' disabled={saving}>
								{saving ? (
									<>
										<Loader size={18} className='spinner-border spinner-border-sm me-2' />
										Se salvează...
									</>
								) : (
									<>
										<Save size={18} />
										Salvează Modificările
									</>
								)}
							</button>
							<Link href='/admin/produse' className='btn btn-outline-secondary'>
								Anulează
							</Link>
							<button type='button' className='btn btn-danger' onClick={handleDelete}>
								<Trash2 size={18} />
								Șterge Produs
							</button>
						</div>
					</div>
				</div>
			</form>
		</AdminLayout>
	);
}
