"use client";
import { useState, useEffect, useRef } from "react";
import { fetchWrapper } from "@/helpers";
import { toast } from "react-toastify";
import Swal from "sweetalert2";
import {
	Upload,
	Trash2,
	ChevronUp,
	ChevronDown,
	Eye,
	EyeOff,
	Image as ImageIcon,
	Plus,
	GripVertical,
} from "lucide-react";

import AdminLayout from "@/components/admin/layout";

export default function AdminBannere() {
	const [banners, setBanners] = useState([]);
	const [loading, setLoading] = useState(true);
	const [uploading, setUploading] = useState(false);
	const fileInputRef = useRef(null);

	const fetchBanners = async () => {
		try {
			const data = await fetchWrapper.get("/api/admin/banners");
			setBanners(data.banners || []);
		} catch {
			toast.error("Eroare la încărcarea bannerelor.");
		} finally {
			setLoading(false);
		}
	};

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

	// ── Salvează ordinea/starea în DB ──
	const saveBanners = async (updatedBanners) => {
		try {
			await fetchWrapper.put("/api/admin/banners", { banners: updatedBanners });
		} catch {
			toast.error("Eroare la salvare.");
		}
	};

	// ── Upload imagine nouă ──
	const handleUpload = async (file, title = "") => {
		if (!file) return;
		setUploading(true);

		const formData = new FormData();
		formData.append("image", file);
		formData.append("title", title);

		try {
               const res = await fetchWrapper.post("/api/admin/banners", formData); 
               
			if (res.success) {
				toast.success("Banner adăugat cu succes!");
				fetchBanners();
			} else {
				toast.error(res.error || "Eroare la upload.");
			}
		} catch {
			toast.error("Eroare la upload.");
		} finally {
			setUploading(false);
		}
	};

	// ── Swal upload cu preview ──
	const openUploadModal = () => {
		Swal.fire({
			title: "",
			width: "600px",
			background: "#ffffff",
			showConfirmButton: true,
			showCancelButton: true,
			confirmButtonText: "Adaugă banner",
			cancelButtonText: "Anulează",
			customClass: {
				popup: "banner-upload-popup",
				confirmButton: "banner-confirm-btn",
				cancelButton: "banner-cancel-btn",
				htmlContainer: "premium-html-container",
			},
			html: `
            <style>
                .banner-upload-popup { border-radius: 16px !important; padding: 0 !important; }
                .banner-upload-container { padding: 40px; text-align: left; }
                .banner-upload-title { font-size: 24px; font-weight: 700; color: #000; margin: 0 0 6px 0; }
                .banner-upload-subtitle { font-size: 14px; color: #888; margin: 0 0 28px 0; }
                .banner-drop-zone {
                    border: 2px dashed #e5e5e5; border-radius: 12px; padding: 40px 20px;
                    text-align: center; cursor: pointer; transition: all 0.2s;
                    background: #fafafa; margin-bottom: 20px;
                }
                .banner-drop-zone:hover { border-color: #000; background: #f5f5f5; }
                .banner-drop-zone.has-file { border-color: #000; border-style: solid; }
                .banner-preview {
                    width: 100%; max-height: 200px; object-fit: cover;
                    border-radius: 8px; display: none; margin-bottom: 12px;
                }
                .banner-preview.visible { display: block; }
                .banner-form-label { display: block; font-size: 13px; font-weight: 600; color: #000; margin-bottom: 6px; }
                .banner-form-input {
                    width: 100%; padding: 12px 14px; border: 2px solid #e5e5e5;
                    border-radius: 10px; font-size: 14px; box-sizing: border-box;
                    font-family: inherit; background: #fafafa;
                }
                .banner-form-input:focus { outline: none; border-color: #000; background: #fff; }
                .banner-confirm-btn {
                    background: #000 !important; color: #fff !important; border: none !important;
                    border-radius: 10px !important; padding: 14px 32px !important;
                    font-size: 15px !important; font-weight: 600 !important;
                }
                .banner-cancel-btn {
                    background: transparent !important; color: #666 !important;
                    border: 2px solid #d0d0d0 !important; border-radius: 10px !important;
                    padding: 14px 32px !important; font-size: 15px !important; font-weight: 600 !important;
                }
            </style>
            <div class="banner-upload-container">
                <h2 class="banner-upload-title">Adaugă banner nou</h2>
                <p class="banner-upload-subtitle">Încarcă o imagine pentru bannerul promoțional</p>

                <img id="banner-preview" class="banner-preview" src="" alt="preview" />

                <div class="banner-drop-zone" id="drop-zone" onclick="document.getElementById('banner-file-input').click()">
                    <div id="drop-zone-content">
                        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5" style="margin-bottom:12px"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                        <p style="color:#999;font-size:14px;margin:0">Click sau trage imaginea aici</p>
                        <p style="color:#ccc;font-size:12px;margin:6px 0 0">JPG, PNG, WEBP — max 10MB</p>
                    </div>
                </div>
                <input type="file" id="banner-file-input" accept="image/*" style="display:none" />

                <div style="margin-top:16px">
                    <label class="banner-form-label">Titlu banner (opțional)</label>
                    <input id="banner-title" class="banner-form-input" placeholder="ex: Reduceri de vară -30%" />
                </div>
            </div>
            `,
			didOpen: () => {
				const fileInput = document.getElementById("banner-file-input");
				const dropZone = document.getElementById("drop-zone");
				const preview = document.getElementById("banner-preview");

				const showPreview = (file) => {
					const reader = new FileReader();
					reader.onload = (e) => {
						preview.src = e.target.result;
						preview.classList.add("visible");
						dropZone.classList.add("has-file");
						document.getElementById("drop-zone-content").style.display = "none";
					};
					reader.readAsDataURL(file);
				};

				fileInput.addEventListener("change", (e) => {
					if (e.target.files[0]) showPreview(e.target.files[0]);
				});

				// Drag & drop pe zona de upload
				dropZone.addEventListener("dragover", (e) => {
					e.preventDefault();
					dropZone.style.borderColor = "#000";
				});
				dropZone.addEventListener("dragleave", () => {
					dropZone.style.borderColor = "#e5e5e5";
				});
				dropZone.addEventListener("drop", (e) => {
					e.preventDefault();
					const file = e.dataTransfer.files[0];
					if (file && file.type.startsWith("image/")) {
						fileInput.files = e.dataTransfer.files;
						showPreview(file);
					}
				});
			},
			preConfirm: () => {
				const fileInput = document.getElementById("banner-file-input");
				const title = document.getElementById("banner-title").value.trim();

				if (!fileInput.files[0]) return Swal.showValidationMessage("Selectează o imagine.");

				return { file: fileInput.files[0], title };
			},
		}).then((result) => {
			if (result.isConfirmed && result.value) {
				handleUpload(result.value.file, result.value.title);
			}
		});
	};

	// ── Toggle activ/inactiv ──
	const toggleActive = async (id) => {
		const updated = banners.map((b) => (b.id === id ? { ...b, active: !b.active } : b));
		setBanners(updated);
		await saveBanners(updated);
		toast.success("Status actualizat.");
	};

	// ── Mută sus ──
	const moveUp = async (index) => {
		if (index === 0) return;
		const updated = [...banners];
		[updated[index - 1], updated[index]] = [updated[index], updated[index - 1]];
		setBanners(updated);
		await saveBanners(updated);
	};

	// ── Mută jos ──
	const moveDown = async (index) => {
		if (index === banners.length - 1) return;
		const updated = [...banners];
		[updated[index], updated[index + 1]] = [updated[index + 1], updated[index]];
		setBanners(updated);
		await saveBanners(updated);
	};

	// ── Șterge ──
	const handleDelete = async (id) => {
		const result = await Swal.fire({
			title: "Ștergi bannerul?",
			text: "Imaginea va fi eliminată din lista de bannere.",
			icon: "warning",
			showCancelButton: true,
			confirmButtonText: "Da, șterge",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#e53e3e",
			cancelButtonColor: "#718096",
			reverseButtons: true,
			focusCancel: true,
		});
		if (!result.isConfirmed) return;

		const res = await fetchWrapper.delete("/api/admin/banners?id=" + id);
		if (res.success) {
			toast.success("Banner șters.");
			fetchBanners();
		}
	};

	// ── Editează titlu ──
	const handleEditTitle = async (banner) => {
		const { value: newTitle } = await Swal.fire({
			title: "Editează titlul",
			input: "text",
			inputValue: banner.title || "",
			inputPlaceholder: "Titlu banner...",
			showCancelButton: true,
			confirmButtonText: "Salvează",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#000",
		});

		if (newTitle !== undefined) {
			const updated = banners.map((b) => (b.id === banner.id ? { ...b, title: newTitle } : b));
			setBanners(updated);
			await saveBanners(updated);
			toast.success("Titlu actualizat.");
		}
	};

	if (loading) return <div style={{ padding: 60, textAlign: "center", color: "#999" }}>Se încarcă...</div>;

	const activeBanners = banners.filter((b) => b.active).length;

	return (
		<AdminLayout>
			<div style={{ padding: "32px 40px", maxWidth: 1100, margin: "0 auto" }}>
				{/* Header */}
				<div
					style={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						marginBottom: 32,
					}}>
					<div>
						<h1 style={{ fontSize: 28, fontWeight: 700, margin: "0 0 6px 0", color: "#000" }}>
							Management Bannere
						</h1>
						<p style={{ fontSize: 14, color: "#888", margin: 0 }}>
							{banners.length} bannere · {activeBanners} active
						</p>
					</div>
					<button
						onClick={openUploadModal}
						disabled={uploading}
						style={{
							display: "flex",
							alignItems: "center",
							gap: 8,
							background: "#000",
							color: "#fff",
							padding: "12px 24px",
							borderRadius: 10,
							border: "none",
							cursor: "pointer",
							fontSize: 14,
							fontWeight: 600,
							opacity: uploading ? 0.6 : 1,
						}}>
						{uploading ? (
							<>⏳ Se încarcă...</>
						) : (
							<>
								<Plus size={16} /> Adaugă banner
							</>
						)}
					</button>
				</div>

				{/* Empty state */}
				{banners.length === 0 ? (
					<div
						style={{
							textAlign: "center",
							padding: "80px 20px",
							background: "#fafafa",
							borderRadius: 16,
							border: "2px dashed #e5e5e5",
						}}>
						<ImageIcon size={48} color='#ccc' style={{ marginBottom: 16 }} />
						<p style={{ color: "#999", fontSize: 15, margin: "0 0 24px" }}>
							Nu există bannere adăugate.
						</p>
						<button
							onClick={openUploadModal}
							style={{
								background: "#000",
								color: "#fff",
								padding: "12px 28px",
								borderRadius: 10,
								border: "none",
								cursor: "pointer",
								fontSize: 14,
								fontWeight: 600,
							}}>
							Adaugă primul banner
						</button>
					</div>
				) : (
					<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
						{banners.map((banner, index) => (
							<div
								key={banner.id}
								style={{
									display: "flex",
									alignItems: "center",
									gap: 16,
									background: "#fff",
									border: banner.active ? "2px solid #000" : "2px solid #e5e5e5",
									borderRadius: 14,
									padding: 16,
									opacity: banner.active ? 1 : 0.6,
									transition: "all 0.2s",
								}}>
								{/* Index */}
								<div
									style={{
										width: 28,
										height: 28,
										background: "#f5f5f5",
										borderRadius: 6,
										display: "flex",
										alignItems: "center",
										justifyContent: "center",
										fontSize: 12,
										fontWeight: 700,
										color: "#888",
										flexShrink: 0,
									}}>
									{index + 1}
								</div>

								{/* Preview imagine */}
								<div
									style={{
										width: 120,
										height: 68,
										flexShrink: 0,
										borderRadius: 8,
										overflow: "hidden",
										background: "#f5f5f5",
										border: "1px solid #e5e5e5",
									}}>
									<img
										src={banner.url}
										alt={banner.title || `Banner ${index + 1}`}
										style={{ width: "100%", height: "100%", objectFit: "cover" }}
									/>
								</div>

								{/* Info */}
								<div style={{ flex: 1, minWidth: 0 }}>
									<div
										style={{
											fontSize: 14,
											fontWeight: 600,
											color: "#000",
											marginBottom: 4,
											whiteSpace: "nowrap",
											overflow: "hidden",
											textOverflow: "ellipsis",
										}}>
										{banner.title || (
											<span style={{ color: "#ccc", fontStyle: "italic" }}>
												Fără titlu
											</span>
										)}
									</div>
									<div style={{ fontSize: 12, color: "#999" }}>
										{banner.active ? (
											<span style={{ color: "#16a34a", fontWeight: 600 }}>
												● Activ
											</span>
										) : (
											<span style={{ color: "#dc2626", fontWeight: 600 }}>
												● Inactiv
											</span>
										)}
										{" · "}
										{new Date(banner.createdAt).toLocaleDateString("ro-RO")}
									</div>
								</div>

								{/* Acțiuni */}
								<div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
									{/* Editează titlu */}
									<button
										onClick={() => handleEditTitle(banner)}
										title='Editează titlu'
										style={btnStyle("#f5f5f5", "#000", "#e5e5e5")}>
										✏️
									</button>

									{/* Toggle activ */}
									<button
										onClick={() => toggleActive(banner.id)}
										title={banner.active ? "Dezactivează" : "Activează"}
										style={btnStyle(
											banner.active ? "#fff7ed" : "#f0fdf4",
											banner.active ? "#ea580c" : "#16a34a",
											banner.active ? "#fed7aa" : "#bbf7d0",
										)}>
										{banner.active ? <EyeOff size={15} /> : <Eye size={15} />}
									</button>

									{/* Sus */}
									<button
										onClick={() => moveUp(index)}
										disabled={index === 0}
										title='Mută sus'
										style={btnStyle("#f5f5f5", "#000", "#e5e5e5", index === 0)}>
										<ChevronUp size={15} />
									</button>

									{/* Jos */}
									<button
										onClick={() => moveDown(index)}
										disabled={index === banners.length - 1}
										title='Mută jos'
										style={btnStyle(
											"#f5f5f5",
											"#000",
											"#e5e5e5",
											index === banners.length - 1,
										)}>
										<ChevronDown size={15} />
									</button>

									{/* Șterge */}
									<button
										onClick={() => handleDelete(banner.id)}
										title='Șterge'
										style={btnStyle("#fff5f5", "#e53e3e", "#fecaca")}>
										<Trash2 size={15} />
									</button>
								</div>
							</div>
						))}
					</div>
				)}

				{/* Footer info */}
				{banners.length > 0 && (
					<div
						style={{
							marginTop: 24,
							padding: "16px 20px",
							background: "#f8f8f8",
							borderRadius: 10,
							fontSize: 13,
							color: "#888",
						}}>
						💡 Ordinea din această listă = ordinea de afișare pe site. Bannerele inactive nu sunt
						afișate vizitatorilor.
					</div>
				)}
			</div>
		</AdminLayout>
	);
}

// Helper stil butoane
function btnStyle(bg, color, border, disabled = false) {
	return {
		width: 34,
		height: 34,
		display: "flex",
		alignItems: "center",
		justifyContent: "center",
		borderRadius: 8,
		border: `1px solid ${border}`,
		background: bg,
		color,
		cursor: disabled ? "not-allowed" : "pointer",
		opacity: disabled ? 0.3 : 1,
		transition: "all 0.2s",
		flexShrink: 0,
		fontSize: 14,
	};
}
