"use client";

import AdminLayout from "@/components/admin/layout";
import { useEffect, useState } from "react";
import { fetchWrapper } from "@/helpers/fetch-wrapper";
import { Package, ShoppingCart, RotateCcw, DollarSign } from "lucide-react";
import Swal from "sweetalert2";

export default function DashboardPage() {
	const [recentOrders, setRecentOrders] = useState([]);
	const [adminStats, setAdminStats] = useState({});
	const [settings, setSettings] = useState([]);
	const [supplierStatus, setSupplierStatus] = useState({ AVEX: true, DEPOX: true });
	const [supplierLoading, setSupplierLoading] = useState({ AVEX: false, DEPOX: false });

	const fetchSupplierStatus = async () => {
		try {
			const resp = await fetchWrapper.get("/api/admin/supplier-status");
			if (resp.success) setSupplierStatus(resp.status);
		} catch (err) {
			console.error("Eroare la preluarea statusului furnizori:", err);
		}
	};

	const handleToggleSupplier = async (supplier) => {
		const newStatus = !supplierStatus[supplier];

		const confirm = await Swal.fire({
			title: `${newStatus ? "Activezi" : "Dezactivezi"} furnizorul ${supplier}?`,
			html: newStatus
				? `Toate produsele <strong>${supplier}</strong> vor deveni <strong style="color:#28a745">vizibile</strong>.`
				: `Toate produsele <strong>${supplier}</strong> vor deveni <strong style="color:#dc3545">invizibile</strong>.`,
			icon: "question",
			showCancelButton: true,
			confirmButtonText: "Da, confirmă",
			cancelButtonText: "Anulează",
			confirmButtonColor: newStatus ? "#28a745" : "#dc3545",
			cancelButtonColor: "#6c757d",
		});

		if (!confirm.isConfirmed) return;

		setSupplierLoading((prev) => ({ ...prev, [supplier]: true }));

		try {
			const resp = await fetchWrapper.post("/api/admin/supplier-visibility", {
				supplier,
				visible: newStatus,
			});

			if (resp.success) {
				setSupplierStatus((prev) => ({ ...prev, [supplier]: newStatus }));
				Swal.fire({
					icon: "success",
					title: "Succes!",
					text: resp.message,
					timer: 2000,
					showConfirmButton: false,
				});
			}
		} catch (err) {
			Swal.fire({ icon: "error", title: "Eroare", text: err.message });
		} finally {
			setSupplierLoading((prev) => ({ ...prev, [supplier]: false }));
		}
	};

	const fetchSettings = async () => {
		try {
			const response = await fetchWrapper.get("/api/admin/settings");
			setSettings(response.settings);
		} catch (error) {
			console.error("Eroare la preluarea setarilor:", error);
		}
	};

	const handleEditSetting = async (setting) => {
		const { value: newValue } = await Swal.fire({
			title: `Editezi setarea ${setting.name}`,
			input: "textarea",
			inputValue: setting.value,
			inputAttributes: {
				autocapitalize: "off",
			},
			showCancelButton: true,
			confirmButtonText: "Salvează",
			cancelButtonText: "Anulează",
			showLoaderOnConfirm: true,
			preConfirm: async (value) => {
				try {
					const response = await fetchWrapper.put(`/api/admin/settings/${setting.id}`, { value: value });

					if (!response.success) {
						throw new Error("Eroare la salvare");
					}

					return value;
				} catch (error) {
					Swal.showValidationMessage(`Eroare: ${error.message}`);
				}
			},
			allowOutsideClick: () => !Swal.isLoading(),
		});

		if (newValue !== undefined) {
			Swal.fire({
				title: "Salvat!",
				text: "Setarea a fost actualizată cu succes.",
				icon: "success",
			});

			fetchSettings();
		}
	};

	const fetchCheck = async () => {
		try {
			const resp = await fetchWrapper.get("/api/admin/authcheck");

			if (resp.status === 401) {
				window.location.href = "/";
				return;
			}
		} catch (error) {
			if (error) {
				window.location.href = "/";
			}
		}
	};

	const fetchStats = async () => {
		try {
			const response = await fetchWrapper.get("/api/admin/getstats");
			setAdminStats({
				totalSalesThisMonth: response.totalSalesThisMonth,
				totalOrdersThisMonth: response.totalOrdersThisMonth,
				totalProducts: response.totalProducts,
				totalReturnsThisMonth: response.totalReturnsThisMonth,
			});
		} catch (error) {
			console.error("Eroare la preluarea statisticilor:", error);
		}
	};

	const fetchRecentOrders = async () => {
		try {
			const response = await fetchWrapper.get("/api/admin/getorders?page=1&limit=5");
			setRecentOrders(response.orders);
			return;
		} catch (error) {
			console.error("Eroare la preluarea comenzilor recente:", error);
		}
	};

	useEffect(() => {
		fetchCheck();
		fetchRecentOrders();
		fetchStats();
		fetchSettings();
		fetchSupplierStatus();
	}, []);

	const stats = [
		{
			title: "Vânzări Totale Luna Curenta",
			value: adminStats.totalSalesThisMonth ? `${adminStats.totalSalesThisMonth} RON` : "Încărcare...",

			positive: true,
			icon: DollarSign,
			iconBg: "#2563eb",
		},
		{
			title: "Comenzi Luna Curenta",
			value: adminStats.totalOrdersThisMonth ? `${adminStats.totalOrdersThisMonth}` : "Încărcare...",

			positive: true,
			icon: ShoppingCart,
			iconBg: "#8b5cf6",
		},
		{
			title: "Produse",
			value: adminStats.totalProducts,

			positive: true,
			icon: Package,
			iconBg: "#06b6d4",
		},
		{
			title: "Retururi",
			value: adminStats.totalReturnsThisMonth ? `${adminStats.totalReturnsThisMonth}` : "Încărcare...",

			positive: false,
			icon: RotateCcw,
			iconBg: "#ef4444",
		},
	];

	return (
		<AdminLayout>
			<div className='page-header'>
				<h1 className='page-title'>Dashboard</h1>
				<p className='page-description'>
					Bine ai venit înapoi! Iată o privire de ansamblu asupra afacerii tale.
				</p>
			</div>

			<div className='stats-grid'>
				{stats.map((stat, index) => {
					const Icon = stat.icon;
					return (
						<div key={index} className='stat-card'>
							<div className='stat-header'>
								<span className='stat-title'>{stat.title}</span>
								<div className='stat-icon' style={{ backgroundColor: stat.iconBg + "20" }}>
									<Icon size={20} style={{ color: stat.iconBg }} />
								</div>
							</div>
							<div className='stat-value'>{stat.value}</div>
						</div>
					);
				})}
			</div>

			<div className='content-card'>
				<div className='card-header'>
					<h2 className='card-title'>Status Furnizori</h2>
				</div>
				<div className='card-body' style={{ display: "flex", gap: "1.5rem", flexWrap: "wrap" }}>
					{["AVEX", "DEPOX"].map((supplier) => (
						<div
							key={supplier}
							style={{
								display: "flex",
								alignItems: "center",
								gap: "1rem",
								padding: "1rem 1.5rem",
								border: "1px solid var(--border-color)",
								borderRadius: "0.75rem",
								minWidth: "220px",
							}}>
							<div>
								<div style={{ fontWeight: 600, fontSize: "1rem" }}>{supplier}</div>
								<div style={{ fontSize: "0.8rem", color: "var(--text-secondary)" }}>
									{supplierStatus[supplier] ? "Produse vizibile" : "Produse ascunse"}
								</div>
							</div>
							<button
								onClick={() => handleToggleSupplier(supplier)}
								disabled={supplierLoading[supplier]}
								style={{
									marginLeft: "auto",
									position: "relative",
									width: "52px",
									height: "28px",
									borderRadius: "999px",
									border: "none",
									cursor: supplierLoading[supplier] ? "not-allowed" : "pointer",
									backgroundColor: supplierStatus[supplier] ? "#28a745" : "#dc3545",
									transition: "background-color 0.2s",
									opacity: supplierLoading[supplier] ? 0.6 : 1,
								}}>
								<span
									style={{
										position: "absolute",
										top: "3px",
										left: supplierStatus[supplier] ? "27px" : "3px",
										width: "22px",
										height: "22px",
										borderRadius: "50%",
										backgroundColor: "white",
										transition: "left 0.2s",
										display: "block",
									}}
								/>
							</button>
						</div>
					))}
				</div>
			</div>

			<div className='content-card'>
				<div className='card-header'>
					<h2 className='card-title'>Setari Generale Site</h2>
				</div>
				<div className='card-body'>
					{settings.map((setting, index) => (
						<div key={index}>
							<strong>{setting.name}: </strong>{" "}
							<button
								className='btn btn-sm btn-primary mt-2'
								style={{ fontSize: 10, height: 8 }}
								onClick={() => handleEditSetting(setting)}>
								Editeaza Setarea
							</button>
							<br />
							{setting.value}
							<br />
							<hr />
						</div>
					))}
				</div>
			</div>

			<div className='content-card'>
				<div className='card-header'>
					<h2 className='card-title'>Comenzi Recente</h2>
					<a href='/admin/comenzi' className='btn btn-primary'>
						Vezi toate
					</a>
				</div>
				<div className='table-responsive'>
					<table className='table'>
						<thead>
							<tr>
								<th>ID Comandă</th>
								<th>Client</th>
								<th>Sumă</th>
								<th>Status</th>
								<th>Actiuni</th>
							</tr>
						</thead>
						<tbody>
							{recentOrders.map((order) => (
								<tr key={order.id}>
									<td>{order.id}</td>
									<td>
										{order.billingType === 0
											? order.pf_nume_familie + " " + order.pf_prenume
											: order.pj_nume_firma}
									</td>
									<td>{order.total} RON</td>
									<td>
										<span
											className={`badge ${
												order.status === "paid"
													? "bg-success"
													: order.status === "pending"
														? "bg-warning"
														: "bg-info"
											}`}>
											{order.status}
										</span>
									</td>
									<td>
										<a
											href={"/admin/comenzi/" + order.id}
											className='btn btn-sm btn-secondary'>
											Vezi Comanda
										</a>
									</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			</div>
		</AdminLayout>
	);
}
