"use client"; 

import { useState, useEffect } from "react";
import AdminLayout from "@/components/admin/layout";
import { Plus, Search, Edit, Trash2, Shield, User } from "lucide-react";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";

export default function UtilizatoriPage() {
	const [users, setUsers] = useState([]);
	const [loading, setLoading] = useState(true);
	const [searchTerm, setSearchTerm] = useState("");

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

	const loadUsers = async (search = "") => {
		try {
			setLoading(true);
			const response = await fetchWrapper.get(`/api/admin/users/list${search ? `?search=${search}` : ""}`);
			setUsers(response.users);
		} catch (error) {
			Swal.fire({
				icon: "error",
				title: "Eroare",
				text: error.message || "Nu s-au putut încărca utilizatorii",
			});
		} finally {
			setLoading(false);
		}
	};

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

		// Debounce search
		const timeoutId = setTimeout(() => {
			loadUsers(value);
		}, 500);

		return () => clearTimeout(timeoutId);
	};

	const handleAddUser = async () => {
		const { value: formValues } = await Swal.fire({
			title: "Adaugă Utilizator Nou",
			html: `
				<input id="swal-email" class="swal2-input" placeholder="Email" type="email">
				<input id="swal-password" class="swal2-input" placeholder="Parolă" type="password">
				<input id="swal-firstName" class="swal2-input" placeholder="Prenume">
				<input id="swal-lastName" class="swal2-input" placeholder="Nume">
				<div style="margin-top: 15px;">
					<label style="display: flex; align-items: center; justify-content: center; gap: 8px; cursor: pointer;">
						<input id="swal-admin" type="checkbox" style="width: 18px; height: 18px; cursor: pointer;">
						<span>Administrator</span>
					</label>
				</div>
			`,
			focusConfirm: false,
			showCancelButton: true,
			confirmButtonText: "Adaugă",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#3b82f6",

			preConfirm: () => {
				const email = document.getElementById("swal-email").value;
				const password = document.getElementById("swal-password").value;
				const firstName = document.getElementById("swal-firstName").value;
				const lastName = document.getElementById("swal-lastName").value;
				const admin = document.getElementById("swal-admin").checked;

				if (!email || !password) {
					Swal.showValidationMessage("Email și parola sunt obligatorii!");
					return false;
				}

				if (password.length < 6) {
					Swal.showValidationMessage("Parola trebuie să aibă cel puțin 6 caractere!");
					return false;
				}

				return { email, password, firstName, lastName, admin };
			},
		});

		if (formValues) {
			try {
				await fetchWrapper.post("/api/admin/users/create", formValues);

				Swal.fire({
					icon: "success",
					title: "Success!",
					text: "Utilizatorul a fost creat cu succes!",
					timer: 2000,
					showConfirmButton: false,
				});

				loadUsers(searchTerm);
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare",
					text: error.message || "Nu s-a putut crea utilizatorul",
				});
			}
		}
	};

	const handleEditUser = async (user) => {
		const { value: formValues } = await Swal.fire({
			title: "Editează Utilizator",
			html: `
				<input id="swal-email" class="swal2-input" placeholder="Email" type="email" value="${user.email}">
				<input id="swal-firstName" class="swal2-input" placeholder="Prenume" value="${user.firstName || ""}">
				<input id="swal-lastName" class="swal2-input" placeholder="Nume" value="${user.lastName || ""}">
				<input id="swal-password" class="swal2-input" placeholder="Parolă nouă (opțional)" type="password">
				<div style="margin-top: 15px;">
					<label style="display: flex; align-items: center; justify-content: center; gap: 8px; cursor: pointer;">
						<input id="swal-admin" type="checkbox" ${
							user.admin ? "checked" : ""
						} style="width: 18px; height: 18px; cursor: pointer;">
						<span>Administrator</span>
					</label>
				</div>
			`,
			focusConfirm: false,
			showCancelButton: true,
			confirmButtonText: "Salvează",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#3b82f6",
			preConfirm: () => {
				const email = document.getElementById("swal-email").value;
				const firstName = document.getElementById("swal-firstName").value;
				const lastName = document.getElementById("swal-lastName").value;
				const password = document.getElementById("swal-password").value;
				const admin = document.getElementById("swal-admin").checked;

				if (!email) {
					Swal.showValidationMessage("Emailul este obligatoriu!");
					return false;
				}

				if (password && password.length < 6) {
					Swal.showValidationMessage("Parola trebuie să aibă cel puțin 6 caractere!");
					return false;
				}

				return { id: user.id, email, firstName, lastName, password, admin };
			},
		});

		if (formValues) {
			try {
				await fetchWrapper.post("/api/admin/users/update", formValues);

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

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

	const handleDeleteUser = async (user) => {
		const result = await Swal.fire({
			title: "Ești sigur?",
			html: `Vrei să ștergi utilizatorul <strong>${user.email}</strong>?<br><small>Această acțiune nu poate fi anulată!</small>`,
			icon: "warning",
			showCancelButton: true,
			confirmButtonColor: "#dc2626",
			cancelButtonColor: "#6b7280",
			confirmButtonText: "Da, șterge!",
			cancelButtonText: "Anulează",
		});

		if (result.isConfirmed) {
			try {
				await fetchWrapper.post("/api/admin/users/delete", { id: user.id });

				Swal.fire({
					icon: "success",
					title: "Șters!",
					text: "Utilizatorul a fost șters cu succes!",
					timer: 2000,
					showConfirmButton: false,
				});

				loadUsers(searchTerm);
			} catch (error) {
				Swal.fire({
					icon: "error",
					title: "Eroare",
					text: error.message || "Nu s-a putut șterge utilizatorul",
				});
			}
		}
	};

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

	return (
		<AdminLayout>
			<div className='page-header'>
				<div>
					<h1 className='page-title'>Utilizatori</h1>
					<p className='page-description'>Gestionează conturile utilizatorilor și permisiunile lor.</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ă utilizatori...'
							value={searchTerm}
							onChange={handleSearch}
						/>
					</div>
					<button className='btn btn-primary' onClick={handleAddUser}>
						<Plus size={18} />
						Adaugă Utilizator
					</button>
				</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>Utilizator</th>
									<th>Email</th>
									<th>Rol</th>
									<th>Comenzi</th>
									<th>Creat la</th>
					
									<th>Acțiuni</th>
								</tr>
							</thead>
							<tbody>
								{users.length === 0 ? (
									<tr>
										<td colSpan='8' style={{ textAlign: "center", padding: "2rem" }}>
											Nu s-au găsit utilizatori
										</td>
									</tr>
								) : (
									users.map((user) => (
										<tr key={user.id}>
											<td>#{user.id}</td>
											<td>
												<div
													style={{
														display: "flex",
														alignItems: "center",
														gap: "0.75rem",
													}}>
													<div
														style={{
															width: "40px",
															height: "40px",
															backgroundColor: user.admin
																? "#3b82f6"
																: "var(--main-bg)",
															borderRadius: "50%",
															display: "flex",
															alignItems: "center",
															justifyContent: "center",
														}}>
														{user.admin ? (
															<Shield
																size={20}
																style={{ color: "#ffffff" }}
															/>
														) : (
															<User
																size={20}
																style={{
																	color: "var(--text-secondary)",
																}}
															/>
														)}
													</div>
													<div>
														<div style={{ fontWeight: "600" }}>
															{user.firstName && user.lastName
																? `${user.firstName} ${user.lastName}`
																: "Anonim"}
														</div>
													</div>
												</div>
											</td>
											<td>{user.email}</td>
											<td>
												{user.admin ? (
													<span className='badge bg-primary'>Administrator</span>
												) : (
													<span className='badge bg-secondary'>Client</span>
												)}
											</td>
											<td>
												<span className='badge bg-info'>
													{user.ordersCount} comenzi
												</span>
											</td>
											<td>{formatDate(user.createdAt)}</td>
											
											<td>
												<button
													className='btn btn-sm btn-info'
													style={{ marginRight: "0.5rem" }}
													onClick={() => handleEditUser(user)}>
													<Edit size={16} />
												</button>
												<button
													className='btn btn-sm btn-danger'
													onClick={() => handleDeleteUser(user)}>
													<Trash2 size={16} />
												</button>
											</td>
										</tr>
									))
								)}
							</tbody>
						</table>
					</div>
				)}
			</div>
		</AdminLayout>
	);
}
