"use client";

import AdminLayout from "@/components/admin/layout";
import Link from "next/link";
import {
	Package,
	Search,
	Edit,
	Trash2,
	AlertCircle,
	ChevronLeft,
	ChevronRight,
	Info,
	Circle,
	Pill,
} from "lucide-react";
import { useState, useEffect } from "react";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";

export default function ProdusePage() {
	const [products, setProducts] = useState([]);
	const [loading, setLoading] = useState(true);
	const [searchTerm, setSearchTerm] = useState("");
	const [currentPage, setCurrentPage] = useState(1);
	const [totalPages, setTotalPages] = useState(1);
	const [totalProducts, setTotalProducts] = useState(0);
	const productsPerPage = 20;

	useEffect(() => {
		loadProducts();
	}, [currentPage, searchTerm]);

	// Debounce search
	useEffect(() => {
		const timer = setTimeout(() => {
			if (currentPage !== 1) {
				setCurrentPage(1); // Reset la prima pagină când se caută
			} else {
				loadProducts();
			}
		}, 500);

		return () => clearTimeout(timer);
	}, [searchTerm]);

	async function loadProducts() {
		try {
			setLoading(true);
			const params = new URLSearchParams({
				page: currentPage,
				limit: productsPerPage,
			});

			if (searchTerm.trim()) {
				params.append("search", searchTerm.trim());
			}

			const response = await fetchWrapper.get(`/api/admin/products?${params}`);
			setProducts(response.products || []);
			setTotalPages(response.totalPages || 1);
			setTotalProducts(response.total || 0);
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: "Nu s-au putut încărca produsele",
				confirmButtonColor: "#dc3545",
			});
			console.error("Eroare la încărcarea produselor:", error);
		} finally {
			setLoading(false);
		}
	}

	function getStockStatus(stock) {
		if (stock === 0 || stock === null) return { text: "Stoc epuizat", class: "bg-danger" };
		if (stock < 5) return { text: "Stoc limitat", class: "bg-warning" };
		return { text: "În stoc", class: "bg-success" };
	}

	async function handleViewProfit(sku, productName, productPrice, productId) {
		try {
			const resp = await fetchWrapper.get(`/api/admin/avex/profit?sku=${sku}`);

			if (!resp.success) {
				throw new Error(resp.data.error || "Eroare la preluarea datelor");
			}

			const avexPrice = parseFloat(resp.data.price);
			const salePrice = parseFloat(productPrice);

			if (isNaN(avexPrice) || isNaN(salePrice)) {
				Swal.fire({
					icon: "warning",
					title: "Date invalide",
					text: "Prețurile nu au putut fi determinate corect.",
				});
				return;
			}

			const profit = salePrice - avexPrice;
			const profitPercent = ((profit / avexPrice) * 100).toFixed(2);
			const color = profit >= 0 ? "#28a745" : "#dc3545";

			const result = await Swal.fire({
				title: productName,
				html: `
				<div style="text-align: left; padding: 10px;">
					<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
						<p style="margin: 8px 0;"><strong>Preț achiziție (AVEX):</strong> ${avexPrice.toFixed(2)} RON</p>
						<p style="margin: 8px 0;"><strong>Preț vânzare actual:</strong> ${salePrice.toFixed(2)} RON</p>
					</div>
					<div style="background: ${color}15; padding: 15px; border-radius: 8px; border-left: 4px solid ${color};">
						<p style="margin: 0;"><strong style="color:${color}">Marjă profit curentă:</strong></p>
						<p style="margin: 5px 0 0 0; font-size: 18px; color:${color}; font-weight: bold;">
							${profit.toFixed(2)} RON (${profitPercent}%)
						</p>
					</div>
				</div>
			`,
				icon: "info",
				showCancelButton: true,
				confirmButtonText: "Editează Marja",
				cancelButtonText: "Închide",
				confirmButtonColor: "#0074d9",
				cancelButtonColor: "#6c757d",
			});

			if (result.isConfirmed) {
				await editProfitMargin(sku, productName, avexPrice, salePrice, productId);
			}
		} catch (err) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: err.message || "A apărut o problemă la conectarea cu API-ul AVEX.",
			});
			console.error("EROARE FRONTEND:", err);
		}
	}

	async function handleViewProfitDepox(sku, productName, productPrice, productId) {
		try {
			const resp = await fetchWrapper.get(`/api/admin/depox/profit?sku=${encodeURIComponent(sku)}`);

			if (!resp.success) {
				throw new Error(resp.error || "Eroare la preluarea datelor DEPOX");
			}

			const depoxPrice = parseFloat(resp.data.price);
			const salePrice = parseFloat(productPrice);

			if (isNaN(depoxPrice) || isNaN(salePrice)) {
				Swal.fire({
					icon: "warning",
					title: "Date invalide",
					text: "Prețurile nu au putut fi determinate.",
				});
				return;
			}

			const profit = salePrice - depoxPrice;
			const profitPercent = ((profit / depoxPrice) * 100).toFixed(2);
			const color = profit >= 0 ? "#28a745" : "#dc3545";

			const result = await Swal.fire({
				title: productName,
				html: `
                         <div style="text-align: left; padding: 10px;">
                              <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                              <p style="margin: 8px 0;"><strong>Preț achiziție (DEPOX):</strong> ${depoxPrice.toFixed(2)} RON</p>
                              <p style="margin: 8px 0;"><strong>Preț vânzare actual:</strong> ${salePrice.toFixed(2)} RON</p>
                              </div>
                              <div style="background: ${color}15; padding: 15px; border-radius: 8px; border-left: 4px solid ${color};">
                              <p style="margin: 0;"><strong style="color:${color}">Marjă profit curentă:</strong></p>
                              <p style="margin: 5px 0 0 0; font-size: 18px; color:${color}; font-weight: bold;">
                                   ${profit.toFixed(2)} RON (${profitPercent}%)
                              </p>
                              </div>
                         </div>
                    `,
				icon: "info",
				showCancelButton: true,
				confirmButtonText: "Editează Marja",
				cancelButtonText: "Închide",
				confirmButtonColor: "#0074d9",
				cancelButtonColor: "#6c757d",
			});

			if (result.isConfirmed) {
				await editProfitMargin(sku, productName, depoxPrice, salePrice, productId);
			}
		} catch (err) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: err.message || "Problemă la conectarea cu feed-ul DEPOX.",
			});
			console.error("EROARE DEPOX:", err);
		}
	}

	async function editProfitMargin(sku, productName, avexPrice, currentSalePrice, productId) {
		const currentProfit = currentSalePrice - avexPrice;
		const currentProfitPercent = ((currentProfit / avexPrice) * 100).toFixed(2);

		const { value: newProfitPercent } = await Swal.fire({
			title: `Editează marja de profit`,
			html: `
			<div style="text-align: left; margin-bottom: 20px;">
				<p style="margin: 5px 0;"><strong>Produs:</strong> ${productName}</p>
				<p style="margin: 5px 0;"><strong>Preț achiziție:</strong> ${avexPrice.toFixed(2)} RON</p>
				<p style="margin: 5px 0;"><strong>Marjă actuală:</strong> ${currentProfitPercent}%</p>
			</div>
			<label for="profit-input" style="display: block; text-align: left; margin-bottom: 8px; font-weight: 500;">
				Introduceți noua marjă de profit (%):
			</label>
		`,
			input: "number",
			inputValue: currentProfitPercent,
			inputAttributes: {
				id: "profit-input",
				step: "0.01",
				min: "-100",
				max: "1000",
				placeholder: "ex: 25.50",
			},
			showCancelButton: true,
			confirmButtonText: "Calculează & Salvează",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#28a745",
			cancelButtonColor: "#6c757d",
			inputValidator: (value) => {
				if (!value) {
					return "Te rog introduce o valoare!";
				}
				const numValue = parseFloat(value);
				if (isNaN(numValue)) {
					return "Te rog introduce un număr valid!";
				}
				if (numValue < -100 || numValue > 1000) {
					return "Marja trebuie să fie între -100% și 1000%!";
				}
			},
			didOpen: () => {
				const input = document.getElementById("profit-input");

				input.addEventListener("input", function () {
					const margin = parseFloat(this.value);
					if (!isNaN(margin)) {
						const newPrice = avexPrice * (1 + margin / 100);
						const previewDiv = document.getElementById("price-preview");

						if (!previewDiv) {
							const preview = document.createElement("div");
							preview.id = "price-preview";
							preview.style.cssText = `
							margin-top: 15px;
							padding: 12px;
							background: #e7f3ff;
							border-radius: 6px;
							border-left: 4px solid #0074d9;
							text-align: left;
						`;
							this.parentElement.appendChild(preview);
						}

						const profitAmount = newPrice - avexPrice;
						const profitColor = profitAmount >= 0 ? "#28a745" : "#dc3545";

						document.getElementById("price-preview").innerHTML = `
						<p style="margin: 5px 0; font-weight: 500;">📊 Preview calcul:</p>
						<p style="margin: 5px 0;">Preț nou de vânzare: <strong>${newPrice.toFixed(2)} RON</strong></p>
						<p style="margin: 5px 0; color: ${profitColor};">
							Profit: <strong>${profitAmount.toFixed(2)} RON</strong> (${margin}%)
						</p>
					`;
					}
				});

				// Trigger initial preview
				input.dispatchEvent(new Event("input"));
			},
		});

		if (newProfitPercent) {
			const marginPercent = parseFloat(newProfitPercent);
			const newSalePrice = avexPrice * (1 + marginPercent / 100);
			const newProfit = newSalePrice - avexPrice;

			// Confirmăm noile valori
			const confirmation = await Swal.fire({
				title: "Confirmă modificarea",
				html: `
				<div style="text-align: left;">
					<p><strong>Produs:</strong> ${productName}</p>
					<hr>
					<p><strong>Preț achiziție:</strong> ${avexPrice.toFixed(2)} RON</p>
					<p><strong>Marjă nouă:</strong> ${marginPercent.toFixed(2)}%</p>
					<p><strong>Preț nou de vânzare:</strong> <span style="color: #0074d9; font-size: 18px;">${newSalePrice.toFixed(
						2,
					)} RON</span></p>
					<p><strong>Profit nou:</strong> <span style="color: #28a745;">${newProfit.toFixed(2)} RON</span></p>
				</div>
			`,
				icon: "question",
				showCancelButton: true,
				confirmButtonText: "Da, salvează",
				cancelButtonText: "Anulează",
				confirmButtonColor: "#28a745",
				cancelButtonColor: "#6c757d",
			});

			if (confirmation.isConfirmed) {
				try {
					// Trimite cererea către backend pentru a actualiza prețul
					const response = await fetchWrapper.post(`/api/admin/products/${productId}`, {
						newPrice: newSalePrice.toFixed(2),
					});

					if (response.success) {
						await Swal.fire({
							icon: "success",
							title: "Succes!",
							text: `Prețul a fost actualizat la ${newSalePrice.toFixed(2)} RON`,
							confirmButtonColor: "#28a745",
						});

						// Reîncarcă pagina sau actualizează datele
						loadProducts();
					} else {
						throw new Error(response.error || "Eroare la salvare");
					}
				} catch (err) {
					Swal.fire({
						icon: "error",
						title: "Eroare la salvare",
						text: err.message || "Nu s-a putut actualiza prețul produsului.",
					});
					console.error("EROARE SALVARE:", err);
				}
			}
		}
	}

	async function handleDelete(id, productName) {
		const result = await Swal.fire({
			title: "Ești sigur?",
			html: `Vrei să ștergi produsul <strong>${productName}</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,
				});

				// Dacă era ultimul produs de pe pagină și nu e prima pagină, mergi la pagina anterioară
				if (products.length === 1 && currentPage > 1) {
					setCurrentPage(currentPage - 1);
				} else {
					loadProducts();
				}
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare",
					text: "Nu s-a putut șterge produsul",
					confirmButtonColor: "#dc3545",
				});
				console.error("Eroare la ștergerea produsului:", error);
			}
		}
	}

	function handlePageChange(newPage) {
		if (newPage >= 1 && newPage <= totalPages) {
			setCurrentPage(newPage);
			window.scrollTo({ top: 0, behavior: "smooth" });
		}
	}

	function renderPaginationButtons() {
		const buttons = [];
		const maxButtons = 5;
		let startPage = Math.max(1, currentPage - Math.floor(maxButtons / 2));
		let endPage = Math.min(totalPages, startPage + maxButtons - 1);

		if (endPage - startPage < maxButtons - 1) {
			startPage = Math.max(1, endPage - maxButtons + 1);
		}

		for (let i = startPage; i <= endPage; i++) {
			buttons.push(
				<button
					key={i}
					className={`btn btn-sm ${i === currentPage ? "btn-primary" : "btn-outline-secondary"}`}
					onClick={() => handlePageChange(i)}
					style={{ minWidth: "40px" }}>
					{i}
				</button>,
			);
		}

		return buttons;
	}

	const startProduct = (currentPage - 1) * productsPerPage + 1;
	const endProduct = Math.min(currentPage * productsPerPage, totalProducts);

	return (
		<AdminLayout>
			<div className='page-header'>
				<div>
					<h1 className='page-title'>Produse</h1>
					<p className='page-description'>
						Gestionează inventarul și produsele tale. Total: {totalProducts} produse
					</p>
				</div>
			</div>

			<div className='content-card'>
				<div className='card-header'>
					<div style={{ backgroundColor: "black", padding: "10px" }}>
						<p style={{ color: "white" }}>Semnificatie culori:</p>
						<br />
						<p style={{ color: "white" }}>
							<Circle
								size={12}
								style={{ color: "yellow" }}
								title='Produs în așteptare de verificare'
							/>
							Produs listat pe marketplace în așteptare de verificare
						</p>
						<p style={{ color: "white" }}>
							<Circle
								size={12}
								style={{ color: "red" }}
								title='Produs în așteptare de verificare'
							/>
							Produs listat pe marketplace RESPINS la verificare
						</p>
					</div>

					<div className='input-group' style={{ maxWidth: "400px", flex: "1" }}>
						<span className='input-group-text'>
							<Search size={18} />
						</span>
						<input
							type='text'
							className='form-control'
							placeholder='Caută produse (nume, SKU, EAN)...'
							value={searchTerm}
							onChange={(e) => setSearchTerm(e.target.value)}
						/>
					</div>
				</div>

				<div className='table-responsive'>
					{loading ? (
						<div style={{ textAlign: "center", padding: "3rem" }}>
							<div className='spinner-border text-primary' role='status'>
								<span className='visually-hidden'>Se încarcă...</span>
							</div>
						</div>
					) : products.length === 0 ? (
						<div style={{ textAlign: "center", padding: "3rem" }}>
							<AlertCircle
								size={48}
								style={{ color: "var(--text-secondary)", marginBottom: "1rem" }}
							/>
							<p style={{ color: "var(--text-secondary)" }}>
								{searchTerm ? "Nu s-au găsit produse" : "Nu există produse adăugate"}
							</p>
						</div>
					) : (
						<>
							<table className='table'>
								<thead>
									<tr>
										<th>ID</th>
										<th>Nume Produs</th>
										<th>Tip Produs</th>
										<th>Categorie</th>
										<th>SKU</th>
										<th>Preț</th>
										<th>Stoc</th>
										<th>Status</th>
										<th>Acțiuni</th>
									</tr>
								</thead>
								<tbody>
									{products.map((product) => {
										const status = getStockStatus(product.stock);
										return (
											<tr key={product.id}>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													#{product.id}
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													<div
														style={{
															display: "flex",
															alignItems: "center",
															gap: "0.75rem",
														}}>
														<div
															style={{
																width: "40px",
																height: "40px",
																backgroundColor: "var(--main-bg)",
																borderRadius: "0.5rem",
																display: "flex",
																alignItems: "center",
																justifyContent: "center",
															}}>
															<Package
																size={20}
																style={{
																	color: "var(--text-secondary)",
																}}
															/>
														</div>
														<span>{product.name}</span>
													</div>
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													{product.listedBy != 0 ? (
														<>
															<span
																className='badge'
																style={{ backgroundColor: "purple" }}>
																MARKETPLACE
															</span>
														</>
													) : (
														<>
															<span
																className='badge'
																style={{ backgroundColor: "black" }}>
																FURNIZORI
															</span>
														</>
													)}
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													{product.categoryName || "-"}
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													<code style={{ fontSize: "0.85rem" }}>
														{product.sku || "-"}
													</code>
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													<strong>
														{product.priceReduced
															? product.priceReduced
															: product.price}{" "}
														RON
													</strong>
													{product.priceReduced && (
														<div>
															<small
																style={{
																	textDecoration: "line-through",
																	color: "var(--text-secondary)",
																}}>
																{product.price} RON
															</small>
														</div>
													)}
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													{product.stock ?? 0}
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													<span className={`badge ${status.class}`}>
														{status.text}
													</span>
												</td>
												<td
													style={{
														backgroundColor:
															product.verified === 0
																? "#FFF6D6"
																: product.verified === 2
																	? "red"
																	: "",
													}}>
													<button
														className='btn btn-sm btn-warning'
														onClick={() => {
															if (product.back_supplier === "AVEX") {
																handleViewProfit(
																	product.sku,
																	product.name,
																	product.price,
																	product.id,
																);
															} else if (
																product.back_supplier === "DEPOX"
															) {
																handleViewProfitDepox(
																	product.sku,
																	product.name,
																	product.price,
																	product.id,
																);
															} else {
																editProfitMargin(
																	product.sku,
																	product.name,
																	product.price,
																	product.id,
																);
															}
														}}
														style={{ marginBottom: 10 }}>
														<Info size={16} /> Marja Profit
													</button>
													<Link
														href={`/admin/produse/${product.id}`}
														className='btn btn-sm btn-info'
														style={{ marginRight: "0.5rem" }}>
														<Edit size={16} />
													</Link>
													<button
														className='btn btn-sm btn-danger'
														onClick={() =>
															handleDelete(product.id, product.name)
														}>
														<Trash2 size={16} />
													</button>
												</td>
											</tr>
										);
									})}
								</tbody>
							</table>

							{/* Pagination */}
							{totalPages > 1 && (
								<div
									style={{
										display: "flex",
										justifyContent: "space-between",
										alignItems: "center",
										padding: "1rem",
										borderTop: "1px solid var(--border-color)",
									}}>
									<div style={{ color: "var(--text-secondary)", fontSize: "0.875rem" }}>
										Afișare {startProduct}-{endProduct} din {totalProducts} produse
									</div>

									<div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
										<button
											className='btn btn-sm btn-outline-secondary'
											onClick={() => handlePageChange(currentPage - 1)}
											disabled={currentPage === 1}
											style={{ minWidth: "40px" }}>
											<ChevronLeft size={16} />
										</button>

										{renderPaginationButtons()}

										<button
											className='btn btn-sm btn-outline-secondary'
											onClick={() => handlePageChange(currentPage + 1)}
											disabled={currentPage === totalPages}
											style={{ minWidth: "40px" }}>
											<ChevronRight size={16} />
										</button>
									</div>
								</div>
							)}
						</>
					)}
				</div>
			</div>
		</AdminLayout>
	);
}
