"use client";

import { useState, useEffect } from "react";
import AdminLayout from "@/components/admin/layout";
import { FolderTree, Plus, Search, Edit, Trash2, FolderOpen, ChevronLeft, ChevronRight } from "lucide-react";
import Swal from "sweetalert2";
import { fetchWrapper } from "@/helpers/fetch-wrapper";

export default function CategoriiPage() {
	const [categories, setCategories] = useState([]);
	const [allCategories, setAllCategories] = useState([]);
	const [loading, setLoading] = useState(true);
	const [searchTerm, setSearchTerm] = useState("");
	const [currentPage, setCurrentPage] = useState(1);
	const [itemsPerPage, setItemsPerPage] = useState(10);

	useEffect(() => {
		loadCategories();
	}, []);

	useEffect(() => {
		setCurrentPage(1); // Reset la pagina 1 când se schimbă căutarea
	}, [searchTerm]);

	const loadCategories = async () => {
		try {
			setLoading(true);
			const data = await fetchWrapper.get("/api/admin/categories");
			setAllCategories(data.allCategories);

			// Flatten pentru tabel - afișăm toate categoriile
			const flattenCategories = (cats, parentName = null) => {
				let result = [];
				cats.forEach((cat) => {
					result.push({ ...cat, parentName });
					if (cat.children && cat.children.length > 0) {
						result = result.concat(flattenCategories(cat.children, cat.name));
					}
				});
				return result;
			};

			setCategories(flattenCategories(data.categories));
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare!",
				text: error.message || "Nu s-au putut încărca categoriile",
			});
		} finally {
			setLoading(false);
		}
	};

	const handleCreate = async () => {
		const { value: formValues } = await Swal.fire({
			title: "Adaugă Categorie Nouă",
			html: `
        <div style="text-align: left;">
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Nume *</label>
          <input id="swal-name" class="swal2-input" placeholder="Nume categorie" style="width: 90%; margin: 0 0 15px 0;">
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Slug *</label>
          <input id="swal-slug" class="swal2-input" placeholder="slug-categorie" style="width: 90%; margin: 0 0 15px 0;">
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Categorie Părinte</label>
          <input 
            id="swal-parent" 
            list="categories-list" 
            class="swal2-input" 
            placeholder="Caută categorie..." 
            style="width: 90%; margin: 0 0 15px 0;"
            autocomplete="off"
          >
          <datalist id="categories-list">
            <option value="">Fără părinte (categorie principală)</option>
            ${allCategories.map((cat) => `<option value="${cat.id}">${cat.name}</option>`).join("")}
          </datalist>
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Title (SEO)</label>
          <input id="swal-title" class="swal2-input" placeholder="Title meta tag" style="width: 90%; margin: 0 0 15px 0;">
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Description (SEO)</label>
          <textarea id="swal-description" class="swal2-textarea" placeholder="Description meta tag" style="width: 90%; margin: 0 0 15px 0; height: 80px;"></textarea>
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Keywords (SEO)</label>
          <input id="swal-keywords" class="swal2-input" placeholder="keyword1, keyword2, keyword3" style="width: 90%; margin: 0;">
        </div>
      `,
			focusConfirm: false,
			showCancelButton: true,
			confirmButtonText: "Creează",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#3b82f6",
			cancelButtonColor: "#6b7280",
			width: "600px",
			customClass: {
				popup: "swal-popup-custom",
			},
			preConfirm: () => {
				const name = document.getElementById("swal-name").value;
				const slug = document.getElementById("swal-slug").value;

				if (!name || !slug) {
					Swal.showValidationMessage("Numele și slug-ul sunt obligatorii!");
					return false;
				}

				return {
					name,
					slug,
					parentID: document.getElementById("swal-parent").value || null,
					title: document.getElementById("swal-title").value || null,
					description: document.getElementById("swal-description").value || null,
					keywords: document.getElementById("swal-keywords").value || null,
				};
			},
		});

		if (formValues) {
			try {
				const data = await fetchWrapper.post("/api/admin/categories/create", formValues);
				Swal.fire({
					icon: "success",
					title: "Succes!",
					text: data.message,
					confirmButtonColor: "#3b82f6",
				});
				loadCategories();
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare!",
					text: error.message || error,
					confirmButtonColor: "#3b82f6",
				});
			}
		}
	};

     const getCategoryLevel = (category) => {
          if (!category.parentID) return "categoryName";      
          if (!category.parentName?.includes(">")) return "subcategoryName"; 
          return "thirdCategoryName";                          
     };

	const handleEditMargin = async (category) => {
		const { value: formValues } = await Swal.fire({
			title: `Marjă profit — ${category.name}`,
			html: `
            <div style="text-align: left;">
                <div style="background: #f8f9fa; padding: 12px; border-radius: 8px; margin-bottom: 15px; font-size: 13px;">
                    <strong>Nivel categorie:</strong><br/>
                    ${category.parentName ? `Subcategorie a: <em>${category.parentName}</em>` : "Categorie principală"}
                </div>

                <label style="display:block; font-weight:600; margin-bottom:5px;">Furnizor</label>
                <select id="swal-supplier" class="swal2-input" style="width:90%; margin: 0 0 15px 0;">
                    <option value="AVEX">AVEX ${category.margin_avex != null ? `(actual: ${category.margin_avex}%)` : "(nesetata inca)"}</option>
                    <option value="DEPOX">DEPOX ${category.margin_depox != null ? `(actual: ${category.margin_depox}%)` : "(nesetata inca)"}</option>
                </select>

                <label style="display:block; font-weight:600; margin-bottom:5px;">Marjă profit (%)</label>
                <input 
                    id="swal-margin" 
                    type="number" 
                    class="swal2-input" 
                    placeholder="ex: 25.50" 
                    step="0.01" min="-100" max="1000"
                    style="width:90%; margin: 0 0 15px 0;"
                    value="${category.margin_avex ?? ""}"
                />
<div style="background:#f8f9fa; padding:12px; border-radius:8px; margin-bottom:15px; font-size:13px;">
    <strong>Se aplică pe:</strong> produsele din <em>${category.name}</em>
    ${category.parentName ? ` (subcategorie a: ${category.parentName})` : " (categorie principală)"}
</div>
                <label style="display:block; font-weight:600; margin-bottom:8px;">
                    <input type="checkbox" id="swal-override" style="margin-right:8px;"/>
                    Suprascrie și produsele cu marjă individuală setată
                </label>
            </div>
        `,
			didOpen: () => {
				// Când se schimbă furnizorul, actualizează valoarea marjei
				document.getElementById("swal-supplier").addEventListener("change", (e) => {
					const marginInput = document.getElementById("swal-margin");
					if (e.target.value === "AVEX") {
						marginInput.value = category.margin_avex ?? "";
					} else {
						marginInput.value = category.margin_depox ?? "";
					}
				});
			},
			focusConfirm: false,
			showCancelButton: true,
			confirmButtonText: "Salvează & Aplică",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#f59e0b",
			cancelButtonColor: "#6b7280",
			width: "550px",
			preConfirm: () => {
				const margin = parseFloat(document.getElementById("swal-margin").value);
				if (isNaN(margin)) {
					Swal.showValidationMessage("Introduceți o marjă validă!");
					return false;
				}
				return {
					supplier: document.getElementById("swal-supplier").value,
					margin,
					categoryLevel: getCategoryLevel(category),
					overrideIndividual: document.getElementById("swal-override").checked,
				};
			},
		});

		if (!formValues) return;

		// Confirmare înainte de aplicare
		const confirm = await Swal.fire({
			title: "Confirmi aplicarea?",
			html: `
            <div style="text-align:left;">
                <p><strong>Categorie:</strong> ${category.name}</p>
                <p><strong>Furnizor:</strong> ${formValues.supplier}</p>
                <p><strong>Marjă nouă:</strong> ${formValues.margin}%</p>
                <p><strong>Nivel:</strong> ${formValues.categoryLevel}</p>
                <p><strong>Suprascrie individuale:</strong> ${formValues.overrideIndividual ? "Da" : "Nu"}</p>
            </div>
        `,
			icon: "question",
			showCancelButton: true,
			confirmButtonText: "Da, aplică",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#f59e0b",
			cancelButtonColor: "#6b7280",
		});

		if (!confirm.isConfirmed) return;

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

		try {
			const data = await fetchWrapper.post("/api/admin/categories/margin", {
				categoryId: category.id,
				supplier: formValues.supplier,
				margin: formValues.margin,
				overrideIndividual: formValues.overrideIndividual,
				categoryLevel: formValues.categoryLevel,
			});

			await Swal.fire({
				icon: "success",
				title: "Succes!",
				html: `
                ${data.message}<br/><br/>
                <small>
                    ✓ Produse găsite: ${data.totalFound ?? 0}<br/>
                    ✓ Produse actualizate: ${data.updatedCount ?? 0}
                    ${data.errors ? `<br/>⚠️ Erori: ${data.errors.length}` : ""}
                </small>
            `,
				confirmButtonColor: "#f59e0b",
			});

			loadCategories(); // reîncarcă să apară marja nouă în tabel
		} catch (err) {
			Swal.fire({ icon: "error", title: "Eroare", text: err.message });
		}
	};

	const handleEdit = async (category) => {
		const { value: formValues } = await Swal.fire({
			title: "Editează Categoria",
			html: `
        <div style="text-align: left;">
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Nume *</label>
          <input id="swal-name" class="swal2-input" value="${category.name || ""}" style="width: 90%; margin: 0 0 15px 0;">
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Slug *</label>
          <input id="swal-slug" class="swal2-input" value="${category.slug || ""}" style="width: 90%; margin: 0 0 15px 0;">
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Categorie Părinte</label>
          <select id="swal-parent" class="swal2-input" style="width: 90%; margin: 0 0 15px 0;">
            <option value="">Fără părinte (categorie principală)</option>
            ${allCategories
				.filter((cat) => cat.id !== category.id)
				.map(
					(cat) =>
						`<option value="${cat.id}" ${cat.id === category.parentID ? "selected" : ""}>${cat.name}</option>`,
				)
				.join("")}
          </select>
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Title (SEO)</label>
          <input id="swal-title" class="swal2-input" value="${category.title || ""}" style="width: 90%; margin: 0 0 15px 0;">
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Description (SEO)</label>
          <textarea id="swal-description" class="swal2-textarea" style="width: 90%; margin: 0 0 15px 0; height: 80px;">${category.description || ""}</textarea>
          
          <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #374151;">Keywords (SEO)</label>
          <input id="swal-keywords" class="swal2-input" value="${category.keywords || ""}" style="width: 90%; margin: 0;">
        </div>
      `,
			focusConfirm: false,
			showCancelButton: true,
			confirmButtonText: "Salvează",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#3b82f6",
			cancelButtonColor: "#6b7280",
			width: "600px",
			preConfirm: () => {
				return {
					name: document.getElementById("swal-name").value,
					slug: document.getElementById("swal-slug").value,
					parentID: document.getElementById("swal-parent").value || null,
					title: document.getElementById("swal-title").value,
					description: document.getElementById("swal-description").value,
					keywords: document.getElementById("swal-keywords").value,
				};
			},
		});

		if (formValues) {
			try {
				const data = await fetchWrapper.put(`/api/admin/categories/${category.id}`, formValues);

				let message = data.message;
				if (data.updatedProducts) {
					message += `\n\n✓ ${data.updatedProducts} produse au fost actualizate automat`;
				}

				Swal.fire({
					icon: "success",
					title: "Succes!",
					html: message.replace(/\n/g, "<br>"),
					confirmButtonColor: "#3b82f6",
				});
				loadCategories();
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare!",
					text: error.message || error,
					confirmButtonColor: "#3b82f6",
				});
			}
		}
	};

	const handleDelete = async (category) => {
		const result = await Swal.fire({
			title: "Ești sigur?",
			html: `
			Vrei să ștergi categoria <strong>"${category.name}"</strong>?<br><br>
			<div style="color: #ef4444; font-weight: 600;">
				⚠️ Atenție: Vor fi șterse și toate subcategoriile și produsele asociate!
			</div>
			<br><small style="color: #6b7280;">Această acțiune nu poate fi anulată.</small>
		`,
			icon: "warning",
			showCancelButton: true,
			confirmButtonColor: "#ef4444",
			cancelButtonColor: "#6b7280",
			confirmButtonText: "Da, șterge tot!",
			cancelButtonText: "Anulează",
		});

		if (result.isConfirmed) {
			try {
				const data = await fetchWrapper.delete(`/api/admin/categories/${category.id}`);
				Swal.fire({
					icon: "success",
					title: "Șters!",
					html: `
					${data.message}<br><br>
					<small>
						✓ ${data.deletedCategories} categorie/categorii<br>
						✓ ${data.deletedProducts} produse
					</small>
				`,
					confirmButtonColor: "#3b82f6",
				});
				loadCategories();
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare!",
					text: error.message || error,
					confirmButtonColor: "#3b82f6",
				});
			}
		}
	};

	// Filtrare și paginare
	const filteredCategories = categories.filter(
		(cat) =>
			cat.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
			cat.slug.toLowerCase().includes(searchTerm.toLowerCase()),
	);

	const totalPages = Math.ceil(filteredCategories.length / itemsPerPage);
	const startIndex = (currentPage - 1) * itemsPerPage;
	const endIndex = startIndex + itemsPerPage;
	const currentCategories = filteredCategories.slice(startIndex, endIndex);

	const handlePageChange = (newPage) => {
		if (newPage >= 1 && newPage <= totalPages) {
			setCurrentPage(newPage);
		}
	};

	const getPageNumbers = () => {
		const pages = [];
		const maxVisible = 5;

		if (totalPages <= maxVisible) {
			for (let i = 1; i <= totalPages; i++) {
				pages.push(i);
			}
		} else {
			if (currentPage <= 3) {
				for (let i = 1; i <= 4; i++) pages.push(i);
				pages.push("...");
				pages.push(totalPages);
			} else if (currentPage >= totalPages - 2) {
				pages.push(1);
				pages.push("...");
				for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
			} else {
				pages.push(1);
				pages.push("...");
				pages.push(currentPage - 1);
				pages.push(currentPage);
				pages.push(currentPage + 1);
				pages.push("...");
				pages.push(totalPages);
			}
		}

		return pages;
	};

	return (
		<AdminLayout>
			<div className='page-header'>
				<div>
					<h1 className='page-title'>Categorii</h1>
					<p className='page-description'>Gestionează categoriile de produse și ierarhia lor.</p>
				</div>
			</div>

			<div className='content-card'>
				<div className='card-header'>
					<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ă categorii...'
							value={searchTerm}
							onChange={(e) => setSearchTerm(e.target.value)}
						/>
					</div>
					<div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
						<select
							className='form-select'
							style={{ width: "auto" }}
							value={itemsPerPage}
							onChange={(e) => {
								setItemsPerPage(Number(e.target.value));
								setCurrentPage(1);
							}}>
							<option value={10}>10 / pagină</option>
							<option value={25}>25 / pagină</option>
							<option value={50}>50 / pagină</option>
							<option value={100}>100 / pagină</option>
						</select>
						<button className='btn btn-primary' onClick={handleCreate}>
							<Plus size={18} />
							Adaugă Categorie
						</button>
					</div>
				</div>

				<div className='table-responsive'>
					{loading ? (
						<div style={{ padding: "3rem", textAlign: "center", color: "var(--text-secondary)" }}>
							Se încarcă categoriile...
						</div>
					) : filteredCategories.length === 0 ? (
						<div style={{ padding: "3rem", textAlign: "center", color: "var(--text-secondary)" }}>
							{searchTerm
								? "Nu s-au găsit categorii."
								: "Nu există categorii. Creează prima categorie!"}
						</div>
					) : (
						<>
							<table className='table'>
								<thead>
									<tr>
										<th>Nume Categorie</th>
										<th>Slug</th>
										<th>Categorie Părinte</th>
										<th>SEO Title</th>
										<th>Marjă AVEX</th>
										<th>Marjă DEPOX</th>
										<th>Acțiuni</th>
										<th>Acțiuni</th>
									</tr>
								</thead>
								<tbody>
									{currentCategories.map((category) => (
										<tr key={category.id}>
											<td>
												<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",
														}}>
														{category.parentID ? (
															<FolderOpen
																size={20}
																style={{ color: "#f59e0b" }}
															/>
														) : (
															<FolderTree
																size={20}
																style={{ color: "#3b82f6" }}
															/>
														)}
													</div>
													<span
														style={{
															fontWeight: category.parentID
																? "normal"
																: "600",
														}}>
														{category.name}
													</span>
												</div>
											</td>
											<td>
												<code
													style={{
														fontSize: "0.875rem",
														color: "var(--text-secondary)",
													}}>
													{category.slug}
												</code>
											</td>
											<td>
												{category.parentName ? (
													<span className='badge bg-secondary'>
														{category.parentName}
													</span>
												) : (
													<span style={{ color: "var(--text-secondary)" }}>
														-
													</span>
												)}
											</td>
											<td
												style={{
													maxWidth: "250px",
													overflow: "hidden",
													textOverflow: "ellipsis",
													whiteSpace: "nowrap",
												}}>
												{category.title || (
													<span style={{ color: "var(--text-secondary)" }}>
														-
													</span>
												)}
											</td>
											<td>
												{category.margin_avex != null ? (
													<span className='badge bg-success'>
														{category.margin_avex}%
													</span>
												) : (
													<span style={{ color: "var(--text-secondary)" }}>
														-
													</span>
												)}
											</td>
											<td>
												{category.margin_depox != null ? (
													<span className='badge bg-info'>
														{category.margin_depox}%
													</span>
												) : (
													<span style={{ color: "var(--text-secondary)" }}>
														-
													</span>
												)}
											</td>
											<td>
												<button
													className='btn btn-sm btn-warning'
													style={{ marginRight: "0.5rem" }}
													onClick={() => handleEditMargin(category)}>
													% Marjă
												</button>
												<button
													className='btn btn-sm btn-info'
													style={{ marginRight: "0.5rem" }}
													onClick={() => handleEdit(category)}>
													<Edit size={16} />
												</button>
												<button
													className='btn btn-sm btn-danger'
													onClick={() => handleDelete(category)}>
													<Trash2 size={16} />
												</button>
											</td>
										</tr>
									))}
								</tbody>
							</table>

							{/* Pagination */}
							<div
								style={{
									display: "flex",
									justifyContent: "space-between",
									alignItems: "center",
									padding: "1rem 1.5rem",
									borderTop: "1px solid var(--border-color)",
								}}>
								<div style={{ color: "var(--text-secondary)", fontSize: "0.875rem" }}>
									Afișare {startIndex + 1} - {Math.min(endIndex, filteredCategories.length)}{" "}
									din {filteredCategories.length} categorii
								</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={{ padding: "0.5rem 0.75rem" }}>
										<ChevronLeft size={16} />
									</button>

									{getPageNumbers().map((page, index) =>
										page === "..." ? (
											<span
												key={`ellipsis-${index}`}
												style={{
													padding: "0.5rem",
													color: "var(--text-secondary)",
												}}>
												...
											</span>
										) : (
											<button
												key={page}
												className={`btn btn-sm ${
													currentPage === page
														? "btn-primary"
														: "btn-outline-secondary"
												}`}
												onClick={() => handlePageChange(page)}
												style={{ minWidth: "2.5rem" }}>
												{page}
											</button>
										),
									)}

									<button
										className='btn btn-sm btn-outline-secondary'
										onClick={() => handlePageChange(currentPage + 1)}
										disabled={currentPage === totalPages}
										style={{ padding: "0.5rem 0.75rem" }}>
										<ChevronRight size={16} />
									</button>
								</div>
							</div>
						</>
					)}
				</div>
			</div>

			<style jsx global>{`
				.swal2-input,
				.swal2-textarea {
					border: 1px solid #e5e7eb;
					border-radius: 0.5rem;
					padding: 0.75rem;
					font-size: 0.875rem;
				}

				.swal2-input:focus,
				.swal2-textarea:focus {
					border-color: #3b82f6;
					box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
					outline: none;
				}

				.swal2-validation-message {
					background-color: #fee;
					color: #c00;
				}
			`}</style>
		</AdminLayout>
	);
}
