"use client"; 

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import AdminLayout from "@/components/admin/layout";
import { Filter, Search, Eye, ChevronLeft, ChevronRight } from "lucide-react";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";

export default function ComenziPage() {
	const router = useRouter();
	const [orders, setOrders] = useState([]);
	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(() => {
		loadOrders();
	}, [pagination.currentPage, statusFilter]);

	const loadOrders = 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/orders/list?${queryParams.toString()}`);

			setOrders(response.orders);
			setPagination(response.pagination);
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: error.message || "Nu s-au putut încărca comenzile",
			});
		} finally {
			setLoading(false);
		}
	};

	const handleSearch = (e) => {
		const value = e.target.value;
		setSearchTerm(value);

		const timeoutId = setTimeout(() => {
			setPagination((prev) => ({ ...prev, currentPage: 1 }));
			loadOrders(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 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" },
			paid: { label: "Plătită", class: "bg-success" },
			processing: { label: "În procesare", class: "bg-info" },
			shipped: { label: "Expediată", class: "bg-primary" },
			delivered: { label: "Livrată", class: "bg-success" },
			cancelled: { label: "Anulată", class: "bg-danger" },
			refunded: { label: "Returnată", class: "bg-secondary" },
		};

		const statusInfo = statusMap[status] || { label: status, class: "bg-secondary" };

		return <span className={`badge ${statusInfo.class}`}>{statusInfo.label}</span>;
	};

	const viewOrderDetails = (orderId) => {
		router.push(`/admin/comenzi/${orderId}`);
	};

	return (
		<AdminLayout>
			<div className='page-header'>
				<div>
					<h1 className='page-title'>Comenzi</h1>
					<p className='page-description'>Vizualizează și gestionează toate comenzile.</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ă comenzi...'
							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 === "paid" ? "btn-success" : "btn-outline-secondary"
							}`}
							onClick={() => handleStatusFilter("paid")}>
							Plătite
						</button>
						<button
							className={`btn ${
								statusFilter === "cancelled" ? "btn-danger" : "btn-outline-secondary"
							}`}
							onClick={() => handleStatusFilter("cancelled")}>
							Anulate
						</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</th>
										<th>Client</th>
										<th>Email</th>
										<th>Tip Facturare</th>
										<th>Produse</th>
										<th>Total</th>
										<th>Data</th>
										<th>Status</th>
										<th>Acțiuni</th>
									</tr>
								</thead>
								<tbody>
									{orders.length === 0 ? (
										<tr>
											<td colSpan='9' style={{ textAlign: "center", padding: "2rem" }}>
												Nu s-au găsit comenzi
											</td>
										</tr>
									) : (
										orders.map((order) => (
											<tr key={order.id}>
												<td style={{ fontWeight: "600" }}>#{order.id}</td>
												<td>{order.customerName}</td>
												<td style={{ color: "var(--text-secondary)" }}>
													{order.customerEmail}
												</td>
												<td>
													<span
														className={`badge ${
															order.billingType === 0
																? "bg-info"
																: "bg-primary"
														}`}>
														{order.billingType === 0
															? "Persoană Fizică"
															: "Persoană Juridică"}
													</span>
												</td>
												<td>
													<span className='badge bg-secondary'>
														{order.itemsCount}{" "}
														{order.itemsCount === 1 ? "produs" : "produse"}
													</span>
												</td>
												<td style={{ fontWeight: "600" }}>
													{parseFloat(order.total).toFixed(2)} RON
												</td>
												<td
													style={{
														color: "var(--text-secondary)",
														fontSize: "0.9em",
													}}>
													{formatDate(order.createdAt)}
												</td>
												<td>{getStatusBadge(order.status)}</td>
												<td>
													<button
														className='btn btn-sm btn-outline-primary'
														onClick={() => viewOrderDetails(order.id)}>
														<Eye
															size={16}
															style={{ marginRight: "0.25rem" }}
														/>
														Detalii
													</button>
												</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} comenzi
								</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;
										// Afișează doar paginile relevante
										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>
	);
}
