"use client"; 

// pages/admin/retururi/index.js
import { useState, useEffect } from "react";
import AdminLayout from "@/components/admin/layout";
import { RotateCcw, AlertCircle, Search, Eye, ChevronLeft, ChevronRight, CheckCircle, XCircle } from "lucide-react";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";

export default function RetururiPage() {
	const [returns, setReturns] = useState([]);
	const [stats, setStats] = useState({
		activeReturns: 0,
		pendingReturns: 0,
		completedThisMonth: 0
	});
	const [loading, setLoading] = useState(true);
	const [searchTerm, setSearchTerm] = useState("");
	const [statusFilter, setStatusFilter] = useState("all");
	const [pagination, setPagination] = useState({
		currentPage: 1,
		totalPages: 1,
		totalItems: 0,
		itemsPerPage: 10
	});

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

	useEffect(() => {
		loadReturns();
	}, [pagination.currentPage, statusFilter]);

	const loadStats = async () => {
		try {
			const response = await fetchWrapper.get("/api/admin/returns/stats");
			setStats(response.stats);
		} catch (error) {
			console.error("Error loading stats:", error);
		}
	};

	const loadReturns = async (search = "") => {
		try {
			setLoading(true);
			const queryParams = new URLSearchParams({
				page: pagination.currentPage,
				limit: pagination.itemsPerPage,
				status: statusFilter
			});

			if (search) {
				queryParams.append('search', search);
			}

			const response = await fetchWrapper.get(
				`/api/admin/returns/list?${queryParams.toString()}`
			);
			
			setReturns(response.returns);
			setPagination(response.pagination);
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: error.message || "Nu s-au putut încărca retururile",
			});
		} finally {
			setLoading(false);
		}
	};

	const handleSearch = (e) => {
		const value = e.target.value;
		setSearchTerm(value);
		
		const timeoutId = setTimeout(() => {
			setPagination(prev => ({ ...prev, currentPage: 1 }));
			loadReturns(value);
		}, 500);
		
		return () => clearTimeout(timeoutId);
	};

	const handleStatusFilter = (status) => {
		setStatusFilter(status);
		setPagination(prev => ({ ...prev, currentPage: 1 }));
	};

	const handlePageChange = (newPage) => {
		if (newPage >= 1 && newPage <= pagination.totalPages) {
			setPagination(prev => ({ ...prev, currentPage: newPage }));
		}
	};

	const viewReturnDetails = async (returnId) => {
		try {
			const response = await fetchWrapper.get(`/api/admin/returns/${returnId}`);
			const returnData = response.return;

			const reasonMap = {
				defect: "Produs defect",
				not_as_described: "Nu corespunde descrierii",
				wrong_item: "Produs greșit",
				damaged: "Deteriorat la livrare",
				changed_mind: "Schimbare de părere",
				other: "Altele"
			};

			const refundMethodMap = {
				cont: "Cont bancar",
				card: "Card",
				voucher: "Voucher"
			};

			const returnMethodMap = {
				ridicare: "Ridicare de la adresă",
				curier: "Trimitere prin curier",
				personal: "Predare personală"
			};

			let productsHtml = "";
			if (returnData.returnedProducts && returnData.returnedProducts.length > 0) {
				productsHtml = `
					<div style="margin-top: 20px; text-align: left;">
						<h4 style="margin-bottom: 10px;">Produse returnate:</h4>
						<table style="width: 100%; border-collapse: collapse; font-size: 0.9em;">
							<thead>
								<tr style="border-bottom: 2px solid #ddd;">
									<th style="padding: 8px; text-align: left;">Produs</th>
									<th style="padding: 8px; text-align: right;">Preț</th>
									<th style="padding: 8px; text-align: center;">Cantitate</th>
									<th style="padding: 8px; text-align: right;">Subtotal</th>
								</tr>
							</thead>
							<tbody>
								${returnData.returnedProducts.map(item => `
									<tr style="border-bottom: 1px solid #eee;">
										<td style="padding: 8px;">${item.name}</td>
										<td style="padding: 8px; text-align: right;">${parseFloat(item.price).toFixed(2)} RON</td>
										<td style="padding: 8px; text-align: center;">${item.quantity}</td>
										<td style="padding: 8px; text-align: right; font-weight: 600;">${(parseFloat(item.price) * parseInt(item.quantity)).toFixed(2)} RON</td>
									</tr>
								`).join('')}
								<tr style="border-top: 2px solid #ddd; font-weight: bold;">
									<td colspan="3" style="padding: 12px; text-align: right;">TOTAL RETUR:</td>
									<td style="padding: 12px; text-align: right; color: #3b82f6; font-size: 1.1em;">${returnData.returnTotal} RON</td>
								</tr>
							</tbody>
						</table>
					</div>
				`;
			}

			let orderInfoHtml = "";
			if (returnData.order) {
				orderInfoHtml = `
					<div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px; text-align: left;">
						<h4 style="margin-bottom: 10px;">Informații Comandă:</h4>
						<p><strong>ID Comandă:</strong> #${returnData.order.id}</p>
						<p><strong>Client:</strong> ${returnData.user.firstName}</p>
						<p><strong>Email:</strong> ${returnData.user.lastName}</p>
						<p><strong>Status Comandă:</strong> ${returnData.order.status}</p>
					</div>
				`;
			}

			let userInfoHtml = "";
			if (returnData.user) {
				userInfoHtml = `
					<div style="margin-top: 20px; padding: 15px; background: #f0f9ff; border-radius: 8px; text-align: left;">
						<h4 style="margin-bottom: 10px;">Cont Utilizator:</h4>
						<p><strong>Nume:</strong> ${returnData.user.firstName} ${returnData.user.lastName}</p>
						<p><strong>Email:</strong> ${returnData.user.email}</p>
						<p><strong>ID User:</strong> #${returnData.user.id}</p>
					</div>
				`;
			}

			let refundInfoHtml = "";
			if (returnData.refundMethod === "cont" && returnData.iban) {
				refundInfoHtml = `
					<div style="margin-top: 20px; padding: 15px; background: #fef3c7; border-radius: 8px; text-align: left;">
						<h4 style="margin-bottom: 10px;">Informații Rambursare:</h4>
						<p><strong>Metoda:</strong> ${refundMethodMap[returnData.refundMethod] || returnData.refundMethod}</p>
						<p><strong>IBAN:</strong> <code style="background: white; padding: 4px 8px; border-radius: 4px;">${returnData.iban}</code></p>
						<p><strong>Titular Cont:</strong> ${returnData.accountName}</p>
					</div>
				`;
			}

			await Swal.fire({
				title: `Retur #${returnData.id}`,
				html: `
					<div style="text-align: left; max-height: 600px; overflow-y: auto;">
						<div style="padding: 15px; background: #fee2e2; border-radius: 8px; margin-bottom: 20px;">
							<h4 style="margin-bottom: 10px; color: #dc2626;">Detalii Retur:</h4>
							<p><strong>Motiv:</strong> ${reasonMap[returnData.reason] || returnData.reason}</p>
							<p><strong>Detalii:</strong> ${returnData.details || "N/A"}</p>
							<p><strong>Metoda Returnare:</strong> ${returnMethodMap[returnData.returnMethod] || returnData.returnMethod}</p>
							<p><strong>Data Creare:</strong> ${new Date(returnData.createdAt).toLocaleDateString("ro-RO", {
								year: "numeric",
								month: "long",
								day: "numeric",
								hour: "2-digit",
								minute: "2-digit"
							})}</p>
						</div>
						${orderInfoHtml}
						${userInfoHtml}
						${refundInfoHtml}
						${productsHtml}
					</div>
				`,
				width: "800px",
				showCloseButton: true,
				showCancelButton: false,
				confirmButtonText: "Închide",
				confirmButtonColor: "#3b82f6"
			});
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: error.message || "Nu s-au putut încărca detaliile returului",
			});
		}
	};

	const handleStatusChange = async (returnId, newStatus) => {
		const statusLabels = {
			approved: "Aprobat",
			rejected: "Respins",
			processing: "În procesare",
			completed: "Finalizat"
		};

		const confirmText = newStatus === "rejected" 
			? "Ești sigur că vrei să respingi acest retur?"
			: `Vrei să marchezi returul ca ${statusLabels[newStatus]}?`;

		const result = await Swal.fire({
			title: "Confirmă acțiunea",
			text: confirmText,
			icon: "question",
			showCancelButton: true,
			confirmButtonColor: newStatus === "rejected" ? "#dc2626" : "#3b82f6",
			cancelButtonColor: "#6b7280",
			confirmButtonText: "Da, confirmă",
			cancelButtonText: "Anulează",
		});

		if (result.isConfirmed) {
			try {
				await fetchWrapper.post("/api/admin/returns/update-status", {
					id: returnId,
					status: newStatus
				});

				Swal.fire({
					icon: "success",
					title: "Success!",
					text: "Statusul returului a fost actualizat!",
					timer: 2000,
					showConfirmButton: false,
				});

				loadReturns(searchTerm);
				loadStats();
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare",
					text: error.message || "Nu s-a putut actualiza statusul",
				});
			}
		}
	};

	const formatDate = (dateString) => {
		const date = new Date(dateString);
		return date.toLocaleDateString("ro-RO", {
			year: "numeric",
			month: "short",
			day: "numeric",
			hour: "2-digit",
			minute: "2-digit"
		});
	};

	const getStatusBadge = (status) => {
		const statusMap = {
			pending: { label: "În așteptare", class: "bg-warning" },
			approved: { label: "Aprobat", class: "bg-info" },
			rejected: { label: "Respins", class: "bg-danger" },
			processing: { label: "În procesare", class: "bg-primary" },
			completed: { label: "Finalizat", class: "bg-success" }
		};

		const statusInfo = statusMap[status] || { label: status, class: "bg-secondary" };
		
		return (
			<span className={`badge ${statusInfo.class}`}>
				{statusInfo.label}
			</span>
		);
	};

	return (
		<AdminLayout>
			<div className='page-header'>
				<div>
					<h1 className='page-title'>Retururi</h1>
					<p className='page-description'>Gestionează cererile de retur și rambursări.</p>
				</div>
			</div>

			<div className='stats-grid' style={{ gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))" }}>
				<div className='stat-card'>
					<div className='stat-header'>
						<span className='stat-title'>Retururi Active</span>
						<div className='stat-icon' style={{ backgroundColor: "#f59e0b20" }}>
							<RotateCcw size={20} style={{ color: "#f59e0b" }} />
						</div>
					</div>
					<div className='stat-value'>{stats.activeReturns}</div>
				</div>

				<div className='stat-card'>
					<div className='stat-header'>
						<span className='stat-title'>În Așteptare</span>
						<div className='stat-icon' style={{ backgroundColor: "#ef444420" }}>
							<AlertCircle size={20} style={{ color: "#ef4444" }} />
						</div>
					</div>
					<div className='stat-value'>{stats.pendingReturns}</div>
				</div>

				<div className='stat-card'>
					<div className='stat-header'>
						<span className='stat-title'>Finalizate Luna Aceasta</span>
						<div className='stat-icon' style={{ backgroundColor: "#22c55e20" }}>
							<CheckCircle size={20} style={{ color: "#22c55e" }} />
						</div>
					</div>
					<div className='stat-value'>{stats.completedThisMonth}</div>
				</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ă retururi...'
							value={searchTerm}
							onChange={handleSearch}
						/>
					</div>
					<div className="btn-group">
						<button 
							className={`btn ${statusFilter === 'all' ? 'btn-primary' : 'btn-outline-secondary'}`}
							onClick={() => handleStatusFilter('all')}>
							Toate
						</button>
						<button 
							className={`btn ${statusFilter === 'pending' ? 'btn-warning' : 'btn-outline-secondary'}`}
							onClick={() => handleStatusFilter('pending')}>
							În așteptare
						</button>
						<button 
							className={`btn ${statusFilter === 'approved' ? 'btn-info' : 'btn-outline-secondary'}`}
							onClick={() => handleStatusFilter('approved')}>
							Aprobate
						</button>
						<button 
							className={`btn ${statusFilter === 'rejected' ? 'btn-danger' : 'btn-outline-secondary'}`}
							onClick={() => handleStatusFilter('rejected')}>
							Respinse
						</button>
					</div>
				</div>

				{loading ? (
					<div style={{ padding: "3rem", textAlign: "center" }}>
						<div className="spinner-border text-primary" role="status">
							<span className="visually-hidden">Loading...</span>
						</div>
					</div>
				) : (
					<>
						<div className='table-responsive'>
							<table className='table'>
								<thead>
									<tr>
										<th>ID Retur</th>
										<th>ID Comandă</th>
										<th>Client</th>
										<th>Produse</th>
										<th>Total Retur</th>
										<th>Motiv</th>
										<th>Data</th>
										<th>Status</th>
										<th>Acțiuni</th>
									</tr>
								</thead>
								<tbody>
									{returns.length === 0 ? (
										<tr>
											<td colSpan="9" style={{ textAlign: "center", padding: "2rem" }}>
												Nu s-au găsit retururi
											</td>
										</tr>
									) : (
										returns.map((returnItem) => {
											const reasonMap = {
												defect: "Produs defect",
												not_as_described: "Nu corespunde descrierii",
												wrong_item: "Produs greșit",
												damaged: "Deteriorat la livrare",
												changed_mind: "Schimbare de părere",
												other: "Altele"
											};

											return (
												<tr key={returnItem.id}>
													<td style={{ fontWeight: "600" }}>#{returnItem.id}</td>
													<td>
														<span className="badge bg-secondary">
															#{returnItem.orderID}
														</span>
													</td>
													<td>
														{returnItem.order ? (
															<div>
																<div style={{ fontWeight: "600" }}>
																	{returnItem.order.client}
																</div>
																<div style={{ fontSize: "0.85em", color: "var(--text-secondary)" }}>
																	{returnItem.order.customerEmail}
																</div>
															</div>
														) : (
															<span style={{ color: "var(--text-secondary)" }}>N/A</span>
														)}
													</td>
													<td>
														<span className="badge bg-info">
															{returnItem.selectedItems.length} {returnItem.selectedItems.length === 1 ? 'produs' : 'produse'}
														</span>
													</td>
													<td style={{ fontWeight: "600", color: "#dc2626" }}>
														{returnItem.returnTotal} RON
													</td>
													<td style={{ color: "var(--text-secondary)", fontSize: "0.9em" }}>
														{reasonMap[returnItem.reason] || returnItem.reason}
													</td>
													<td style={{ color: "var(--text-secondary)", fontSize: "0.9em" }}>
														{formatDate(returnItem.createdAt)}
													</td>
													<td>
														{getStatusBadge(returnItem.status)}
													</td>
													<td>
														<div style={{ display: "flex", gap: "0.5rem" }}>
															<button 
																className='btn btn-sm btn-outline-primary'
																onClick={() => viewReturnDetails(returnItem.id)}
																title="Vezi detalii">
																<Eye size={16} />
															</button>
															{returnItem.status === 'pending' && (
																<>
																	<button
																		className='btn btn-sm btn-outline-success'
																		onClick={() => handleStatusChange(returnItem.id, 'approved')}
																		title="Aprobă">
																		<CheckCircle size={16} />
																	</button>
																	<button 
																		className='btn btn-sm btn-outline-danger'
																		onClick={() => handleStatusChange(returnItem.id, 'rejected')}
																		title="Respinge">
																		<XCircle size={16} />
																	</button>
																</>
															)}
															{returnItem.status === 'approved' && (
																<button
																	className='btn btn-sm btn-success'
																	onClick={() => handleStatusChange(returnItem.id, 'completed')}
																	title="Marchează ca finalizat">
																	Finalizează
																</button>
															)}
														</div>
													</td>
												</tr>
											);
										})
									)}
								</tbody>
							</table>
						</div>

						{/* Pagination */}
						{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.9em" }}>
									Afișare {((pagination.currentPage - 1) * pagination.itemsPerPage) + 1} - {Math.min(pagination.currentPage * pagination.itemsPerPage, pagination.totalItems)} din {pagination.totalItems} retururi
								</div>
								
								<div className="btn-group">
									<button 
										className="btn btn-outline-secondary btn-sm"
										onClick={() => handlePageChange(pagination.currentPage - 1)}
										disabled={pagination.currentPage === 1}>
										<ChevronLeft size={16} />
									</button>
									
									{[...Array(pagination.totalPages)].map((_, index) => {
										const pageNum = index + 1;
										if (
											pageNum === 1 ||
											pageNum === pagination.totalPages ||
											(pageNum >= pagination.currentPage - 1 && pageNum <= pagination.currentPage + 1)
										) {
											return (
												<button
													key={pageNum}
													className={`btn btn-sm ${pageNum === pagination.currentPage ? 'btn-primary' : 'btn-outline-secondary'}`}
													onClick={() => handlePageChange(pageNum)}>
													{pageNum}
												</button>
											);
										} else if (
											pageNum === pagination.currentPage - 2 ||
											pageNum === pagination.currentPage + 2
										) {
											return <span key={pageNum} style={{ padding: "0 0.5rem" }}>...</span>;
										}
										return null;
									})}
									
									<button 
										className="btn btn-outline-secondary btn-sm"
										onClick={() => handlePageChange(pagination.currentPage + 1)}
										disabled={pagination.currentPage === pagination.totalPages}>
										<ChevronRight size={16} />
									</button>
								</div>
							</div>
						)}
					</>
				)}
			</div>
		</AdminLayout>
	);
}