"use client";

import { useState, useEffect } from "react";
import { fetchWrapper } from "@/helpers";
import DashboardNav from "@/components/othersPages/dashboard/DashboardNav";
import Image from "next/image";
import Link from "next/link";
import ProductEditModal from "@/components/ProductEditModal"; // importă componenta
import ProductAddModal from "@/components/ProductAddModal";

// Toasts 
import { toast } from "react-toastify";
import Swal from "sweetalert2"; 

// Icons
import { Edit, Pencil, DollarSign, Package, Trash, Plus } from "lucide-react";

export default function Marketplace() {
	const [userData, setUserData] = useState([]);
	const [marketplaceAvatar, setMarketplaceAvatar] = useState();
	const [listedProducts, setListedProducts] = useState([]);
	const [stats, setStats] = useState({});
	
	// Modal state
	const [isEditModalOpen, setIsEditModalOpen] = useState(false);
	const [selectedProduct, setSelectedProduct] = useState(null);

     const [isAddModalOpen, setIsAddModalOpen] = useState(false);
     const [categories, setCategories] = useState([]);

     const fetchCategories = async () => {
          const data = await fetchWrapper.get("/api/users/marketplace/categories");
          setCategories(data);
     };

	const fetchUserData = async () => {
		const data = await fetchWrapper.get("/api/users/getdata");
		setUserData(data[0].userData);
		setMarketplaceAvatar(data[0].userData.marketplace_avatar);
	};

	const fetchMarketplaceProducts = async () => {
		const data = await fetchWrapper.get("/api/users/marketplace/products");
		setListedProducts(data[0].listedProducts);

		setStats({
			soldTotal: data[0].soldTotal,
			soldUnits: data[0].soldUnits,
			listedCount: data[0].listedProducts.length,
			verifiedCount: data[0].verifiedCount,
			unverifiedCount: data[0].unverifiedCount,
		});
	};

	useEffect(() => {
		fetchUserData();
		fetchMarketplaceProducts();
          fetchCategories();
	}, []);

     const handleAddProduct = async (formData) => {
          try {
               const response = await fetchWrapper.put('/api/users/marketplace/products', formData);
               
               if (response.success) {
                    toast.success('Produsul a fost adăugat cu succes! Așteaptă aprobarea administratorului.');
                    setIsAddModalOpen(false);
                    fetchMarketplaceProducts();
               } else {
                    toast.error(response.error || 'Eroare la adăugarea produsului.');
               }
          } catch (error) {
               console.error(error);
               toast.error('Eroare la adăugarea produsului.');
          }
     };

	const deleteMyProduct = async (productID) => {
		Swal.fire({
			title: 'Sunteți sigur?',
			text: 'Doriți să ștergeți produsul de pe marketplace-ul nostru? Această acțiune este ireversibilă.',
			icon: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#d33',
			cancelButtonColor: '#3085d6',
			confirmButtonText: 'Da, șterge!',
			cancelButtonText: 'Anulează'
		}).then(async (result) => {
			if (result.isConfirmed) {
				const deleteResponse = await fetchWrapper.delete('/api/users/marketplace/products', { id: productID }); 
				if(deleteResponse.success) {
					toast.success('Produsul a fost șters cu succes.'); 
					fetchMarketplaceProducts(); 
				}
			}
		});
	};

	const editProduct = (productID) => {
		const product = listedProducts.find(p => p.id === productID);
		setSelectedProduct(product);
		setIsEditModalOpen(true);
	};

	const handleSaveProduct = async (formData) => {
		try {
			const response = await fetchWrapper.post('/api/users/marketplace/products', formData);
			
			if (response.success) {
				toast.success('Produsul a fost actualizat cu succes!');
				setIsEditModalOpen(false);
				fetchMarketplaceProducts();
			} else {
				toast.error(response.error || 'Eroare la actualizarea produsului.');
			}
		} catch (error) {
			console.error(error);
			toast.error('Eroare la actualizarea produsului.');
		}
	};

	const editMarketplaceAvatar = () => {
		const input = document.createElement("input");
		input.type = "file";
		input.accept = "image/jpeg,image/png,image/webp";

		input.onchange = async (e) => {
			const file = e.target.files[0];
			if (!file) return;

			if (!["image/jpeg", "image/png", "image/webp"].includes(file.type)) {
				alert("Format invalid. Doar JPG/PNG/WEBP.");
				return;
			}
			if (file.size > 5 * 1024 * 1024) {
				alert("Imagine prea mare. Max 5MB.");
				return;
			}

			const formData = new FormData();
			formData.append("avatar", file);

			const response = await fetchWrapper.post("/api/users/marketplace/avatar", formData);

			if (response?.url) {
				setMarketplaceAvatar(response.url);
			}
		};

		input.click();
	};

	const isReduced = (product) => {
		return product.priceReduced && parseFloat(product.priceReduced) < parseFloat(product.price);
	};

	return (
		<>
			<div className='tf-page-title'>
				<div className='container-full'>
					<div className='heading text-center'>Contul Meu</div>
				</div>
			</div>
			<section className='flat-spacing-11'>
				<style jsx>{`
					.price-wrapper {
						display: flex;
						align-items: center;
						gap: 8px;
					}
					.price-original {
						text-decoration: line-through;
						color: #999;
						font-size: 14px;
					}
					.price-reduced {
						color: #ff4444;
						font-weight: 600;
					}
					.discount-badge {
						display: inline-block;
						background: linear-gradient(135deg, #ff4444 0%, #ff6b6b 100%);
						color: white;
						padding: 4px 8px;
						borderRadius: 4px;
						font-size: 11px;
						font-weight: 600;
						text-transform: uppercase;
						letter-spacing: 0.5px;
						margin-left: 8px;
						box-shadow: 0 2px 4px rgba(255, 68, 68, 0.3);
					}
				`}</style>
				<div className='container'>
					<div className='row'>
						<div className='col-lg-3'>
							<DashboardNav userData={userData} />
						</div>
						<div className='col-lg-9'>
							<center>
								<div
									className='d-flex justify-content-center align-items-center position-relative'
									style={{ width: "120px", height: "120px" }}>
									<Image
										src={marketplaceAvatar}
										alt='Marketplace Avatar'
										fill
										className='rounded-circle border shadow'
										style={{ objectFit: "cover" }}
									/>

									<div
										className='position-absolute bottom-0 end-0 bg-white rounded-circle p-2 shadow'
										style={{ cursor: "pointer" }}
										onClick={() => editMarketplaceAvatar()}>
										<Pencil />
									</div>
								</div>
								<br />
								<b style={{ marginTop: 10 }}>{userData.nume_firma}</b>
								<p>CUI: {userData.cui_firma}</p>
								<br />
								<br />

								<div className='row g-3' style={{ marginBottom: 30 }}>
									<div className='col-12 col-md-6'>
										<div
											className='card shadow-sm h-100 border-0'
											style={{ overflow: "hidden" }}>
											<div
												className='d-flex align-items-center p-3'
												style={{
													background:
														"linear-gradient(135deg, #0ea5a4 0%, #06b6d4 100%)",
													color: "white",
												}}>
												<div
													className='d-flex align-items-center justify-content-center rounded-circle me-3'
													style={{
														width: 56,
														height: 56,
														background: "rgba(255,255,255,0.15)",
														backdropFilter: "blur(4px)",
													}}>
													<DollarSign size={28} strokeWidth={1.5} />
												</div>

												<div className='flex-grow-1'>
													<div
														className='small text-uppercase'
														style={{ opacity: 0.95 }}>
														Produse vândute în valoare de
													</div>
													<div className='h5 mb-0 fw-bold'>
														{stats.soldTotal} RON{" "}
													</div>
												</div>
											</div>
										</div>
									</div>

									<div className='col-12 col-md-6'>
										<div
											className='card shadow-sm h-100 border-0'
											style={{ overflow: "hidden" }}>
											<div
												className='d-flex align-items-center p-3'
												style={{
													background:
														"linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)",
													color: "white",
												}}>
												<div
													className='d-flex align-items-center justify-content-center rounded-circle me-3'
													style={{
														width: 56,
														height: 56,
														background: "rgba(255,255,255,0.12)",
													}}>
													<Package size={26} strokeWidth={1.5} />
												</div>

												<div className='flex-grow-1'>
													<div
														className='small text-uppercase'
														style={{ opacity: 0.95 }}>
														Produse listate în marketplace
													</div>
													<div className='h5 mb-0 fw-bold'>
														{stats.listedCount} produse
													</div>
												</div>

												<div className='ms-3 d-none d-sm-block text-end'>
													<div
														className='small'
														style={{ color: "white !important" }}>
														Active / Inactive: {stats.verifiedCount} /{" "}
														{stats.unverifiedCount}
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>

                                        <div style={{ marginBottom: 20, textAlign: 'right' }}>
                                             <button
                                                  className='btn btn-primary'
                                                  style={{
                                                       borderRadius: 50,
                                                       backgroundColor: '#10b981',
                                                       color: 'white',
                                                       border: 'none',
                                                       padding: '12px 24px',
                                                       fontSize: '14px',
                                                       fontWeight: 600
                                                  }}
                                                  onClick={() => setIsAddModalOpen(true)}>
                                                  <Plus style={{ display: 'inline', marginRight: 8 }} size={18} />
                                                  Adaugă Produs Nou
                                             </button>
                                        </div>
								<div className='my-account-content account-order'>
									<div className='wrap-account-order'>
										<table>
											<thead>
												<tr>
													<th className='fw-6'>#ID</th>
													<th className='fw-6'>Produs</th>
													<th className='fw-6'>Status</th>
													<th className='fw-6'>Preț</th>
													<th className='fw-6'>Stock</th>
													<th className='fw-6'>Acțiuni</th>
												</tr>
											</thead>
											<tbody>
												{listedProducts.length > 0 ? (
													listedProducts.map((product) => (
														<tr key={product.id}>
															<td className='order-number'>
																#{product.id}
															</td>
															<td className='order-date'>
																<Link
																	href={"/" + product.url}
																	className='img-box'>
																	<Image
																		alt='img-product'
																		src={
																			product.images
																				?.split("|")
																				.filter(Boolean)[0]
																		}
																		width={40}
																		height={40}
																		style={{
																			objectFit: "cover",
																		}}
																	/>{" "}
																	{product.name}
																</Link>
															</td>
															<td className='order-status'>
																{product.verified === 1 ? (
																	<span style={{ color: "green" }}>
																		PUBLICAT
																	</span>
																) : (
																	product.rejectReason.length > 0 ? (
																		<span style={{ color: "red" }}>
																			Respins: {product.rejectReason}
																		</span>
																	) : (
																		<span style={{ color: "orange" }}>În verificare administrator</span>
																	)
																)}
															</td>
															<td className='order-total'>
																{isReduced(product) ? (
																	<div className='price-wrapper'>
																		<span className='price-original'>
																			{parseFloat(
																				product.price
																			).toFixed(2)}{" "}
																			RON
																		</span>
																		<span className='price-reduced'>
																			{parseFloat(
																				product.priceReduced
																			).toFixed(2)}{" "}
																			RON
																		</span>
																	</div>
																) : (
																	<span>
																		{parseFloat(
																			product.price
																		).toFixed(2)}{" "}
																		RON
																	</span>
																)}
															</td>
															<td className='order-stock'>
																{product.stock > 0 ? (
																	<span style={{ color: "green" }}>
																		În stoc ({product.stock})
																	</span>
																) : (
																	<span style={{ color: "red" }}>
																		Indisponibil
																	</span>
																)}
															</td>
															<td className='order-actions'>
																<button
																	className='btn btn-primary'
																	style={{
																		marginRight: 10,
																		borderRadius: 50,
																		backgroundColor: "white",
																		color: "black",
																		border: "1px solid black",
																		marginBottom: 10,
																	}}
																	onClick={() =>
																		editProduct(product.id)
																	}
																	disabled={
																		product.verified === 1
																			? false
																			: true
																	}>
																	{product.verified === 1 ? (
																		<>
																			<Edit /> Editează produs
																		</>
																	) : (
																		"În așteptare"
																	)}
																</button>

																<button
																	className='btn btn-primary'
																	style={{
																		marginRight: 10,
																		borderRadius: 50,
																		backgroundColor: "white",
																		color: "red",
																		border: "1px solid red",
																		marginBottom: 10,
																	}}
																	onClick={() =>
																		deleteMyProduct(product.id)
																	}
																	disabled={
																		product.verified === 1
																			? false
																			: true
																	}>
																	{product.verified === 1 ? (
																		<>
																			<Trash /> Șterge produs
																		</>
																	) : (
																		"În așteptare"
																	)}
																</button>
															</td>
														</tr>
													))
												) : (
													<tr>
														<td colSpan='6' className='text-center'>
															Nu aveți niciun produs listat în marketplace.
														</td>
													</tr>
												)}
											</tbody>
										</table>
									</div>
								</div>
							</center>
						</div>
					</div>
				</div>
			</section>

			{/* Modal */}
			<ProductEditModal
				product={selectedProduct}
				isOpen={isEditModalOpen}
				onClose={() => setIsEditModalOpen(false)}
				onSave={handleSaveProduct}
			/>

               <ProductAddModal
                    isOpen={isAddModalOpen}
                    onClose={() => setIsAddModalOpen(false)}
                    onSave={handleAddProduct}
                    categories={categories}
               />
		</>
	);
}