// pages/admin/comenzi/[id].js
"use client"; 

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import AdminLayout from "@/components/admin/layout";
import { ArrowLeft, Package, User, MapPin, Phone, Mail, FileText, Download, Edit } from "lucide-react";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";

export default function OrderDetailsPage({ params }) {
	const router = useRouter();
	const { id } = params; 
	const [order, setOrder] = useState(null);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		if (id) {
			loadOrderDetails();
		}
	}, [id]);

	const loadOrderDetails = async () => {
		try {
			setLoading(true);
			const response = await fetchWrapper.get(`/api/admin/orders/${id}`);
			setOrder(response.order);
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: error.message || "Nu s-au putut încărca detaliile comenzii",
			});
		} finally {
			setLoading(false);
		}
	};

	const handleStatusChange = async () => {
		const statusOptions = {
			pending: "În așteptare",
			paid: "Plătită",
			processing: "În procesare",
			shipped: "Expediată",
			delivered: "Livrată",
			cancelled: "Anulată",
			refunded: "Returnată"
		};

		const { value: newStatus } = await Swal.fire({
			title: "Schimbă Status Comandă",
			input: "select",
			inputOptions: statusOptions,
			inputValue: order.status,
			showCancelButton: true,
			confirmButtonText: "Salvează",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#3b82f6",
			inputValidator: (value) => {
				if (!value) {
					return "Trebuie să selectezi un status!";
				}
			}
		});

		if (newStatus && newStatus !== order.status) {
			try {
				await fetchWrapper.post("/api/admin/orders/update-status", {
					id: order.id,
					status: newStatus
				});

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

				loadOrderDetails();
			} 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: "long",
			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}`} style={{ fontSize: "1em", padding: "0.5em 1em" }}>
				{statusInfo.label}
			</span>
		);
	};

	if (loading) {
		return (
			<AdminLayout>
				<div style={{ padding: "3rem", textAlign: "center" }}>
					<div className="spinner-border text-primary" role="status">
						<span className="visually-hidden">Loading...</span>
					</div>
				</div>
			</AdminLayout>
		);
	}

	if (!order) {
		return (
			<AdminLayout>
				<div style={{ padding: "3rem", textAlign: "center" }}>
					<h3>Comanda nu a fost găsită</h3>
					<button className="btn btn-primary" onClick={() => router.push('/admin/comenzi')}>
						Înapoi la Comenzi
					</button>
				</div>
			</AdminLayout>
		);
	}

	return (
		<AdminLayout>
			<div className='page-header'>
				<div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
					<button 
						className="btn btn-outline-secondary"
						onClick={() => router.push('/admin/comenzi')}>
						<ArrowLeft size={18} />
					</button>
					<div>
						<h1 className='page-title'>Comanda #{order.id}</h1>
						<p className='page-description'>
							Plasată pe {formatDate(order.createdAt)}
						</p>
					</div>
				</div>
				<div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
					{getStatusBadge(order.status)}
					<button className="btn btn-primary" onClick={handleStatusChange}>
						<Edit size={18} style={{ marginRight: "0.5rem" }} />
						Schimbă Status
					</button>
				</div>
			</div>

			<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.5rem", marginBottom: "1.5rem" }}>
				{/* Informații Client */}
				<div className='content-card'>
					<div className='card-header'>
						<h2 className='card-title'>
							<User size={20} style={{ marginRight: "0.5rem" }} />
							Informații Client
						</h2>
					</div>
					<div style={{ padding: "1.5rem" }}>
						{order.billingType === 0 ? (
							// Persoană Fizică
							<>
								<div style={{ marginBottom: "1rem" }}>
									<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
										NUME COMPLET
									</div>
									<div style={{ fontSize: "1.1em" }}>
										{order.pf_prenume} {order.pf_nume_familie}
									</div>
								</div>
								<div style={{ marginBottom: "1rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
									<Mail size={16} color="var(--text-secondary)" />
									<div>{order.pf_email}</div>
								</div>
								<div style={{ marginBottom: "1rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
									<Phone size={16} color="var(--text-secondary)" />
									<div>{order.pf_numar_telefon}</div>
								</div>
								<div style={{ marginBottom: "1rem" }}>
									<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
										<MapPin size={16} />
										ADRESĂ LIVRARE
									</div>
									<div>{order.pf_adresa}</div>
									<div>{order.pf_judet_oras}, {order.pf_tara}</div>
								</div>
								{order.pf_mentiuni && (
									<div>
										<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
											MENȚIUNI
										</div>
										<div style={{ padding: "0.75rem", backgroundColor: "var(--main-bg)", borderRadius: "0.5rem" }}>
											{order.pf_mentiuni}
										</div>
									</div>
								)}
							</>
						) : (
							// Persoană Juridică
							<>
								<div style={{ marginBottom: "1rem" }}>
									<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
										NUME FIRMĂ
									</div>
									<div style={{ fontSize: "1.1em", fontWeight: "600" }}>
										{order.pj_nume_firma}
									</div>
								</div>
								<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem", marginBottom: "1rem" }}>
									<div>
										<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
											CUI
										</div>
										<div>{order.pj_cui}</div>
									</div>
									<div>
										<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
											NR. REG. COM.
										</div>
										<div>{order.pj_nr_reg}</div>
									</div>
								</div>
								<div style={{ marginBottom: "1rem" }}>
									<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
										BANCA / IBAN
									</div>
									<div>{order.pj_banca}</div>
									<div style={{ fontFamily: "monospace", fontSize: "0.9em" }}>{order.pj_iban}</div>
								</div>
								<div style={{ marginBottom: "1rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
									<Mail size={16} color="var(--text-secondary)" />
									<div>{order.pj_email}</div>
								</div>
								<div style={{ marginBottom: "1rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
									<Phone size={16} color="var(--text-secondary)" />
									<div>{order.pj_numar_telefon}</div>
								</div>
								<div style={{ marginBottom: "1rem" }}>
									<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
										<MapPin size={16} />
										ADRESĂ SEDIU
									</div>
									<div>{order.pj_adresa}</div>
									<div>{order.pj_localitate}, {order.pj_judet}</div>
								</div>
								{order.pj_adresa_livrare && (
									<div style={{ marginBottom: "1rem" }}>
										<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
											<Package size={16} />
											ADRESĂ LIVRARE
										</div>
										<div>{order.pj_adresa_livrare}</div>
									</div>
								)}
								{order.pj_mentiuni && (
									<div>
										<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
											MENȚIUNI
										</div>
										<div style={{ padding: "0.75rem", backgroundColor: "var(--main-bg)", borderRadius: "0.5rem" }}>
											{order.pj_mentiuni}
										</div>
									</div>
								)}
							</>
						)}
					</div>
				</div>

				{/* Informații Comandă */}
				<div className='content-card'>
					<div className='card-header'>
						<h2 className='card-title'>
							<FileText size={20} style={{ marginRight: "0.5rem" }} />
							Detalii Comandă
						</h2>
					</div>
					<div style={{ padding: "1.5rem" }}>
						<div style={{ marginBottom: "1rem" }}>
							<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
								TIP FACTURARE
							</div>
							<span className={`badge ${order.billingType === 0 ? 'bg-info' : 'bg-primary'}`}>
								{order.billingType === 0 ? 'Persoană Fizică' : 'Persoană Juridică'}
							</span>
						</div>
						
						{order.user && (
							<div style={{ marginBottom: "1rem" }}>
								<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
									CONT UTILIZATOR
								</div>
								<div>
									{order.user.firstName} {order.user.lastName}
								</div>
								<div style={{ fontSize: "0.9em", color: "var(--text-secondary)" }}>
									{order.user.email}
								</div>
								<div style={{ fontSize: "0.85em", color: "var(--text-secondary)" }}>
									ID: #{order.user.id}
								</div>
							</div>
						)}

						<div style={{ marginBottom: "1rem" }}>
							<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
								Netopia NTP ID
							</div>
							<div style={{ fontFamily: "monospace", fontSize: "0.85em", wordBreak: "break-all" }}>
								{order.netopia_ntpID}
							</div>
						</div>

                              <div style={{ marginBottom: "1rem" }}>
							<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
								Netopia Payment ID
							</div>
							<div style={{ fontFamily: "monospace", fontSize: "0.85em", wordBreak: "break-all" }}>
								{order.netopia_payment_id}
							</div>
						</div>

						{order.bill && (
							<div style={{ marginBottom: "1rem" }}>
								<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
									FACTURĂ
								</div>
								<div style={{ marginBottom: "0.5rem" }}>
									Serie: <strong>{order.bill_series}</strong> / Număr: <strong>{order.bill_number}</strong>
								</div>
								<a 
									href={order.bill} 
									target="_blank" 
									rel="noopener noreferrer"
									className="btn btn-sm btn-outline-primary">
									<Download size={14} style={{ marginRight: "0.5rem" }} />
									Descarcă Factură
								</a>
							</div>
						)}

                              {order.awbUrl && (
							<div style={{ marginBottom: "1rem" }}>
								<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
									AWB
								</div>
								<div style={{ marginBottom: "0.5rem" }}>
									Curier: <strong>{order.awb}</strong> Numar: <strong>{order.awbNumber}</strong>
								</div>
								<a 
									href={order.awbUrl} 
									target="_blank" 
									rel="noopener noreferrer"
									className="btn btn-sm btn-outline-primary">
									<Download size={14} style={{ marginRight: "0.5rem" }} />
									Vezi AWB
								</a>
							</div>
						)}

						{order.certificate && (
							<div style={{ marginBottom: "1rem" }}>
								<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
									CERTIFICAT
								</div>
								<a 
									href={order.certificate} 
									target="_blank" 
									rel="noopener noreferrer"
									className="btn btn-sm btn-outline-secondary">
									<Download size={14} style={{ marginRight: "0.5rem" }} />
									Descarcă Certificat
								</a>
							</div>
						)}

						<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem", marginTop: "1.5rem", paddingTop: "1.5rem", borderTop: "1px solid var(--border-color)" }}>
							<div>
								<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
									CREAT LA
								</div>
								<div style={{ fontSize: "0.9em" }}>{formatDate(order.createdAt)}</div>
							</div>
							<div>
								<div style={{ fontWeight: "600", color: "var(--text-secondary)", fontSize: "0.85em", marginBottom: "0.25rem" }}>
									ACTUALIZAT LA
								</div>
								<div style={{ fontSize: "0.9em" }}>{formatDate(order.updatedAt)}</div>
							</div>
						</div>
					</div>
				</div>
			</div>

			{/* Produse Comandate */}
			<div className='content-card'>
				<div className='card-header'>
					<h2 className='card-title'>
						<Package size={20} style={{ marginRight: "0.5rem" }} />
						Produse Comandate
					</h2>
				</div>

				<div className='table-responsive'>
					<table className='table'>
						<thead>
							<tr>
								<th>Produs</th>
								<th>SKU</th>
								<th>EAN</th>
								<th>Furnizor</th>
								<th>Preț Unitar</th>
								<th>Cantitate</th>
								<th>Subtotal</th>
							</tr>
						</thead>
						<tbody>
							{order.items.map((item, index) => (
								<tr key={index}>
									<td>
										<div style={{ fontWeight: "600" }}>{item.name}</div>
										{item.url && (
											<div style={{ fontSize: "0.85em", color: "var(--text-secondary)" }}>
												/{item.url}
											</div>
										)}
									</td>
									<td style={{ fontFamily: "monospace", fontSize: "0.9em" }}>
										{item.sku}
									</td>
									<td style={{ fontFamily: "monospace", fontSize: "0.9em" }}>
										{item.ean}
									</td>
									<td>
										<span className="badge bg-secondary">{item.supplier}</span>
									</td>
									<td style={{ fontWeight: "600" }}>
										{parseFloat(item.price).toFixed(2)} RON
									</td>
									<td>
										<span className="badge bg-info">{item.quantity}</span>
									</td>
									<td style={{ fontWeight: "600" }}>
										{(parseFloat(item.price) * parseInt(item.quantity)).toFixed(2)} RON
									</td>
								</tr>
							))}
						</tbody>
						<tfoot>
							<tr style={{ borderTop: "2px solid var(--border-color)" }}>
								<td colSpan="6" style={{ textAlign: "right", fontWeight: "600", fontSize: "1.1em" }}>
									SUBTOTAL:
								</td>
								<td style={{ fontWeight: "600", fontSize: "1.1em" }}>
									{order.subtotal} RON
								</td>
							</tr>
							<tr>
								<td colSpan="6" style={{ textAlign: "right", fontWeight: "600", fontSize: "1.2em" }}>
									TOTAL:
								</td>
								<td style={{ fontWeight: "700", fontSize: "1.3em", color: "#3b82f6" }}>
									{order.total} RON
								</td>
							</tr>
						</tfoot>
					</table>
				</div>
			</div>
		</AdminLayout>
	);
}