"use client";
import { useEffect, useState } from "react";
import Slider from "rc-slider";

export default function ShopFilter({ products = [], setFilteredProducts }) {
	const allPrices = products.map((p) => parseFloat(p.price)).filter(Boolean);
	const minPrice = allPrices.length ? Math.floor(Math.min(...allPrices)) : 0;
	const maxPrice = allPrices.length ? Math.ceil(Math.max(...allPrices)) : 1000;

	const [onlyDiscounted, setOnlyDiscounted] = useState(false);

	const [price, setPrice] = useState([minPrice, maxPrice]);
	const [selectedAvailability, setSelectedAvailability] = useState("all");

	const allSuppliers = [...new Set(products.map((p) => p.back_supplier).filter(Boolean))];
	const [selectedSuppliers, setSelectedSuppliers] = useState([]);

	const priceRanges = [
		{ label: "Sub 50", min: 0, max: 50 },
		{ label: "50 - 100", min: 50, max: 100 },
		{ label: "100 - 200", min: 100, max: 200 },
		{ label: "200 - 500", min: 200, max: 500 },
		{ label: "500 - 1.000", min: 500, max: 1000 },
		{ label: "1.000 - 1.500", min: 1000, max: 1500 },
		{ label: "1.500 - 2.000", min: 1500, max: 2000 },
		{ label: "2.000 - 3.000", min: 2000, max: 3000 },
	];

	const [selectedRanges, setSelectedRanges] = useState([]);
	const [useCustomRange, setUseCustomRange] = useState(false);

	const handleSelectRange = (range) => {
		setUseCustomRange(false);
		setSelectedRanges((prev) =>
			prev.some((r) => r.label === range.label)
				? prev.filter((r) => r.label !== range.label)
				: [...prev, range],
		);
	};

	const handleCustomRange = (checked) => {
		setUseCustomRange(checked);
		if (checked) {
			setSelectedRanges([]);
		}
	};

	const handleSelectSupplier = (supplier) => {
		setSelectedSuppliers((prev) =>
			prev.includes(supplier) ? prev.filter((s) => s !== supplier) : [...prev, supplier],
		);
	};

	const clearFilter = () => {
		setPrice([minPrice, maxPrice]);
		setSelectedAvailability("all");
		setSelectedSuppliers([]);
		setSelectedRanges([]);
		setUseCustomRange(false);
		setOnlyDiscounted(false);
	};

	useEffect(() => {
		let result = [...products];

		// ── PREȚ ──
		if (useCustomRange) {
			result = result.filter((p) => {
				const ep = parseFloat(p.priceReduced ?? p.price);
				return ep >= price[0] && ep <= price[1];
			});
		} else if (selectedRanges.length > 0) {
			result = result.filter((p) => {
				const ep = parseFloat(p.priceReduced ?? p.price);
				return selectedRanges.some((r) => ep >= r.min && ep < r.max);
			});
		}

		// ── DISPONIBILITATE ──
		if (selectedAvailability === "in_stock") {
			result = result.filter((p) => p.stock > 0);
		} else if (selectedAvailability === "out_of_stock") {
			result = result.filter((p) => !p.stock || p.stock <= 0);
		}

		if (onlyDiscounted) {
			result = result.filter((p) => p.priceReduced && parseFloat(p.priceReduced) < parseFloat(p.price));
		}

		// ── SUPPLIER ──
		if (selectedSuppliers.length > 0) {
			result = result.filter((p) => selectedSuppliers.includes(p.back_supplier));
		}

		setFilteredProducts(result);
	}, [price, selectedRanges, useCustomRange, selectedAvailability, selectedSuppliers, onlyDiscounted, products]);

	const inStockCount = products.filter((p) => p.stock > 0).length;
	const outOfStockCount = products.filter((p) => !p.stock || p.stock <= 0).length;

	return (
		<div className='offcanvas offcanvas-start canvas-filter' id='filterShop'>
			<div className='canvas-wrapper'>
				<header className='canvas-header'>
					<div className='filter-icon'>
						<span className='icon icon-filter' />
						<span>Filtre</span>
					</div>
					<span className='icon-close icon-close-popup' data-bs-dismiss='offcanvas' aria-label='Close' />
				</header>

				<div className='canvas-body'>
					{/* ── PREȚ ── */}
					<div className='widget-facet wrap-price'>
						<div
							className='facet-title'
							data-bs-target='#price'
							data-bs-toggle='collapse'
							aria-expanded='true'
							aria-controls='price'>
							<span>Preț</span>
							<span className='icon icon-arrow-up' />
						</div>
						<div id='price' className='collapse show'>
							{/* Intervale predefinite */}
							<ul className='tf-filter-group mb_20'>
								{priceRanges.map((range) => {
									const count = products.filter((p) => {
										const ep = parseFloat(p.priceReduced ?? p.price);
										return ep >= range.min && ep < range.max;
									}).length;

									return (
										<li
											key={range.label}
											className='list-item d-flex gap-12 align-items-center'
											onClick={() => handleSelectRange(range)}
											style={{ cursor: "pointer" }}>
											<input
												type='checkbox'
												className='tf-check'
												readOnly
												checked={selectedRanges.some(
													(r) => r.label === range.label,
												)}
											/>
											<label className='label' style={{ cursor: "pointer" }}>
												{range.label}{" "}
												<span style={{ color: "#999" }}>({count})</span>
											</label>
										</li>
									);
								})}
							</ul>

							{/* Separator */}
							<hr style={{ margin: "12px 0", borderColor: "#eee" }} />

							{/* Interval custom cu slider */}
							<div className='widget-price filter-price'>
								<li
									className='list-item d-flex gap-12 align-items-center mb_12'
									onClick={() => handleCustomRange(!useCustomRange)}
									style={{ cursor: "pointer", listStyle: "none" }}>
									<input
										type='checkbox'
										className='tf-check'
										readOnly
										checked={useCustomRange}
									/>
									<label className='label' style={{ cursor: "pointer" }}>
										Interval personalizat
									</label>
								</li>

								<Slider
									range
									min={minPrice}
									max={maxPrice}
									value={price}
									onChange={(val) => {
										setPrice(val);
										setUseCustomRange(true);
										setSelectedRanges([]);
									}}
									disabled={!useCustomRange}
								/>
								<div className='box-title-price' style={{ marginTop: "10px" }}>
									<div className='caption-price d-flex align-items-center gap-12'>
										<input
											type='number'
											value={price[0]}
											onChange={(e) => {
												setPrice([Number(e.target.value), price[1]]);
												setUseCustomRange(true);
												setSelectedRanges([]);
											}}
											style={{
												width: "80px",
												padding: "4px 8px",
												border: "1px solid #ddd",
												borderRadius: "4px",
												textAlign: "center",
											}}
										/>
										<span>-</span>
										<input
											type='number'
											value={price[1]}
											onChange={(e) => {
												setPrice([price[0], Number(e.target.value)]);
												setUseCustomRange(true);
												setSelectedRanges([]);
											}}
											style={{
												width: "80px",
												padding: "4px 8px",
												border: "1px solid #ddd",
												borderRadius: "4px",
												textAlign: "center",
											}}
										/>
									</div>
								</div>
							</div>
						</div>
					</div>

					<div className='widget-facet'>
						<div
							className='facet-title'
							data-bs-target='#discounted'
							data-bs-toggle='collapse'
							aria-expanded='true'
							aria-controls='discounted'>
							<span>Reduceri</span>
							<span className='icon icon-arrow-up' />
						</div>
						<div id='discounted' className='collapse show'>
							<ul className='tf-filter-group mb_36'>
								<li
									className='list-item d-flex gap-12 align-items-center'
									onClick={() => setOnlyDiscounted((prev) => !prev)}
									style={{ cursor: "pointer" }}>
									<input
										type='checkbox'
										className='tf-check'
										readOnly
										checked={onlyDiscounted}
									/>
									<label className='label' style={{ cursor: "pointer" }}>
										<span style={{ color: "red", fontWeight: "600" }}>
											Doar produse la reducere
										</span>
										&nbsp;
										<span style={{ color: "#999" }}>
											(
											{
												products.filter(
													(p) =>
														p.priceReduced &&
														parseFloat(p.priceReduced) < parseFloat(p.price),
												).length
											}
											)
										</span>
									</label>
								</li>
							</ul>
						</div>
					</div>

					{/* ── DISPONIBILITATE ── */}
					<div className='widget-facet'>
						<div
							className='facet-title'
							data-bs-target='#availability'
							data-bs-toggle='collapse'
							aria-expanded='true'
							aria-controls='availability'>
							<span>Disponibilitate</span>
							<span className='icon icon-arrow-up' />
						</div>
						<div id='availability' className='collapse show'>
							<ul className='tf-filter-group mb_36'>
								{[
									{ value: "all", label: "Toate", count: products.length },
									{ value: "in_stock", label: "În stoc", count: inStockCount },
									{ value: "out_of_stock", label: "Stoc epuizat", count: outOfStockCount },
								].map((opt) => (
									<li
										key={opt.value}
										className='list-item d-flex gap-12 align-items-center'
										onClick={() => setSelectedAvailability(opt.value)}
										style={{ cursor: "pointer" }}>
										<input
											type='radio'
											className='tf-check'
											readOnly
											checked={selectedAvailability === opt.value}
										/>
										<label className='label' style={{ cursor: "pointer" }}>
											{opt.label} ({opt.count})
										</label>
									</li>
								))}
							</ul>
						</div>
					</div>

					{/* ── SUPPLIER ── */}
					{allSuppliers.length > 0 && (
						<div className='widget-facet'>
							<div
								className='facet-title'
								data-bs-target='#supplier'
								data-bs-toggle='collapse'
								aria-expanded='true'
								aria-controls='supplier'>
								<span>Furnizor</span>
								<span className='icon icon-arrow-up' />
							</div>
							<div id='supplier' className='collapse show'>
								<ul className='tf-filter-group current-scrollbar mb_36'>
									{allSuppliers.map((supplier) => (
										<li
											key={supplier}
											className='list-item d-flex gap-12 align-items-center'
											onClick={() => handleSelectSupplier(supplier)}
											style={{ cursor: "pointer" }}>
											<input
												type='checkbox'
												className='tf-check'
												readOnly
												checked={selectedSuppliers.includes(supplier)}
											/>
											<label className='label' style={{ cursor: "pointer" }}>
												{supplier} (
												{
													products.filter((p) => p.back_supplier === supplier)
														.length
												}
												)
											</label>
										</li>
									))}
								</ul>
							</div>
						</div>
					)}

					{/* ── CLEAR ── */}
					<div className='mt-5'>
						<a
							className='tf-btn style-2 btn-fill rounded animate-hover-btn'
							onClick={clearFilter}
							style={{ cursor: "pointer" }}>
							Șterge filtrele
						</a>
					</div>
				</div>
			</div>
		</div>
	);
}
