"use client";
import { useContextElement } from "@/context/Context";
import Image from "next/image";
import Link from "next/link";

import { ShieldCheck } from 'lucide-react'; 
import { useState, useEffect } from 'react'; 
export default function Cart() {
	const { cartProducts, setCartProducts } = useContextElement();
	
      const [cartItems, setCartItems] = useState([]);
          const [totalPrice, setTotalPrice] = useState([]); 
     
          useEffect(() => {
             
               const cartProducts = JSON.parse(localStorage.getItem("cartList")); 
               if (cartProducts.length >= 1) {
             
                    const validIds = cartProducts
                         .map(item => item.id)  
                         .filter(id => /^\d+$/.test(id)); 
          
                    if (validIds.length) {
                         fetch(`/api/productsdatabyids?ids=${validIds.join(",")}`)
                              .then((res) => res.json())
                              .then((data) => {
                                   
                                   setCartItems(data.wishlistProducts);
                                   const totalPrice = data.wishlistProducts.reduce((sum, product) => sum + parseFloat(product.price), 0);
                                  
                                   setTotalPrice(totalPrice); 
                              })
                              .catch((err) => console.error("Error fetching products:", err));
                    } else {
                         setCartItems([]); 
                    }
               } else {
                    setCartItems([]);
               }
          }, [cartProducts]);
     
     
          const setQuantity = (id, quantity) => {
               if (quantity >= 1) {
                    const item = cartProducts.filter((elm) => elm.id == id)[0];
                    const items = [...cartProducts];
                    const itemIndex = items.indexOf(item);
                    item.quantity = quantity;
                    items[itemIndex] = item;
                    setCartProducts(items);
               }
          };
          
          const removeItem = (id) => {
               setCartProducts((pre) => [...pre.filter((elm) => elm.id != id)]);
          };

	return (
		<section className='flat-spacing-11'>
			<div className='container'>
				{/* <div className="tf-page-cart text-center mt_140 mb_200">
              <h5 className="mb_24">Your cart is empty</h5>
              <p className="mb_24">You may check out all the available products and buy some in the shop</p>
              <Link href={`/shop-default`} className="tf-btn btn-sm radius-3 btn-fill btn-icon animate-hover-btn">Return to shop<i className="icon icon-arrow1-top-left"></i></Link>
          </div> */}

				<div className='tf-page-cart-wrap'>
					<div className='tf-page-cart-item'>
						<form onSubmit={(e) => e.preventDefault()}>
							<table className='tf-table-page-cart'>
								<thead>
									<tr>
										<th>Produs</th>
										<th>Pret</th>
										<th>Cantitate</th>
										<th>Total</th>
									</tr>
								</thead>
								<tbody>
									{cartItems.map((elm, i) => (
										<tr
											key={i}
											className='tf-cart-item file-delete'
										>
											<td className='tf-cart-item_product'>
												<Link
													href={`/${elm.url}`}
													className='img-box'
												>
													<Image
														alt='img-product'
														src={
															elm.images?.split('|').filter(Boolean)[0]
														}
														width={
															668
														}
														height={
															932
														}
                                                                      style={{
                                                                           objectFit:
                                                                                "cover",
                                                                      }}
													/>
												</Link>
												<div className='cart-info'>
													<Link
														href={`/${elm.url}`}
														className='cart-title link'
													>
														{
															elm.name
														}
													</Link>
													<div className='cart-meta-variant'>
														Variation 
													</div>
													<span
														className='remove-cart link remove'
														onClick={() =>
															removeItem(
																elm.id
															)
														}
													>
														Sterge
													</span>
												</div>
											</td>
											<td
												className='tf-cart-item_price'
												cart-data-title='Price'
											>
												<div className='cart-price'>
													{elm.price}
												
												</div>
											</td>
											<td
												className='tf-cart-item_quantity'
												cart-data-title='Quantity'
											>
												<div className='cart-quantity'>
													<div className='wg-quantity'>
														<span
															className='btn-quantity minus-btn'
															onClick={() =>
                                                                                setQuantity(
                                                                                     elm.id,
                                                                                     cartProducts.find(product => product.id === elm.id)?.quantity || 0 -
                                                                                          1
                                                                                )
                                                                           }
														>
															<svg
																className='d-inline-block'
																width={
																	9
																}
																height={
																	1
																}
																viewBox='0 0 9 1'
																fill='currentColor'
															>
																<path d='M9 1H5.14286H3.85714H0V1.50201e-05H3.85714L5.14286 0L9 1.50201e-05V1Z' />
															</svg>
														</span>
														<input
															type='text'
															name='number'
															value={
                                                                                cartProducts.find(product => product.id === elm.id)?.quantity || 0
                                                                           }
															min={
																1
															}
															onChange={(
                                                                                e
                                                                           ) =>
                                                                                setQuantity(
                                                                                     elm.id,
                                                                                     e
                                                                                          .target
                                                                                          .value /
                                                                                          1,
                                                                                )
                                                                           }
														/>
														<span
															className='btn-quantity plus-btn'
															onClick={() =>
                                                                                setQuantity(
                                                                                     elm.id,
                                                                                     cartProducts.find(product => product.id === elm.id)?.quantity || 0 -
                                                                                          1
                                                                                )
                                                                           }
														>
															<svg
																className='d-inline-block'
																width={
																	9
																}
																height={
																	9
																}
																viewBox='0 0 9 9'
																fill='currentColor'
															>
																<path d='M9 5.14286H5.14286V9H3.85714V5.14286H0V3.85714H3.85714V0H5.14286V3.85714H9V5.14286Z' />
															</svg>
														</span>
													</div>
												</div>
											</td>
											<td
												className='tf-cart-item_total'
												cart-data-title='Total'
											>
												<div
													className='cart-total'
													style={{
														minWidth:
															"60px",
													}}
												>
													{elm.price} RON
												</div>
											</td>
										</tr>
									))}
								</tbody>
							</table>
							{!cartProducts.length && (
								<>
									<div className='row align-items-center mb-5'>
										<div className='col-6 fs-18'>
                                                       Coșul tău de cumpărături este gol. 
										</div>
										<div className='col-6'>
											<Link
												href={`/shop-default`}
												className='tf-btn btn-fill animate-hover-btn radius-3 w-100 justify-content-center'
												style={{
													width: "fit-content",
												}}
											>
												Vezi produse
											</Link>
										</div>
									</div>
								</>
							)}
							
						</form>
					</div>
					<div className='tf-page-cart-footer'>
						<div className='tf-cart-footer-inner'>
			
							<div className='tf-page-cart-checkout'>
			
	
								<div className='tf-cart-totals-discounts'>
									<h3>Total</h3>
									<span className='total-value'>
										x RON
									</span>
								</div>
				
								<div className='cart-checkbox'>
									<input
										type='checkbox'
										className='tf-check'
										id='check-agree'
									/>
									<label
										htmlFor='check-agree'
										className='fw-4'
									>
										Sunt de acord cu 
										<Link
											href={`/termeni-si-conditii`}
										>
											termenii si conditiile
										</Link>
									</label>
								</div>
								<div className='cart-checkout-btn'>
									<Link
										href={`/checkout`}
										className='tf-btn w-100 btn-fill animate-hover-btn radius-3 justify-content-center'
									>
										<span>Check out</span>
									</Link>
								</div>
								<div className='tf-page-cart_imgtrust'>
									<p className='text-center fw-6'>
                                                  <ShieldCheck /> Plata securizata garantata prin <Link href="https://stripe.com">Stripe</Link>
									</p>
									<div className='cart-list-social'>
										<div className='payment-item'>
											<svg
												viewBox='0 0 38 24'
												xmlns='http://www.w3.org/2000/svg'
												role='img'
												width={38}
												height={24}
												aria-labelledby='pi-visa'
											>
												<title id='pi-visa'>
													Visa
												</title>
												<path
													opacity='.07'
													d='M35 0H3C1.3 0 0 1.3 0 3v18c0 1.7 1.4 3 3 3h32c1.7 0 3-1.3 3-3V3c0-1.7-1.4-3-3-3z'
												/>
												<path
													fill='#fff'
													d='M35 1c1.1 0 2 .9 2 2v18c0 1.1-.9 2-2 2H3c-1.1 0-2-.9-2-2V3c0-1.1.9-2 2-2h32'
												/>
												<path
													d='M28.3 10.1H28c-.4 1-.7 1.5-1 3h1.9c-.3-1.5-.3-2.2-.6-3zm2.9 5.9h-1.7c-.1 0-.1 0-.2-.1l-.2-.9-.1-.2h-2.4c-.1 0-.2 0-.2.2l-.3.9c0 .1-.1.1-.1.1h-2.1l.2-.5L27 8.7c0-.5.3-.7.8-.7h1.5c.1 0 .2 0 .2.2l1.4 6.5c.1.4.2.7.2 1.1.1.1.1.1.1.2zm-13.4-.3l.4-1.8c.1 0 .2.1.2.1.7.3 1.4.5 2.1.4.2 0 .5-.1.7-.2.5-.2.5-.7.1-1.1-.2-.2-.5-.3-.8-.5-.4-.2-.8-.4-1.1-.7-1.2-1-.8-2.4-.1-3.1.6-.4.9-.8 1.7-.8 1.2 0 2.5 0 3.1.2h.1c-.1.6-.2 1.1-.4 1.7-.5-.2-1-.4-1.5-.4-.3 0-.6 0-.9.1-.2 0-.3.1-.4.2-.2.2-.2.5 0 .7l.5.4c.4.2.8.4 1.1.6.5.3 1 .8 1.1 1.4.2.9-.1 1.7-.9 2.3-.5.4-.7.6-1.4.6-1.4 0-2.5.1-3.4-.2-.1.2-.1.2-.2.1zm-3.5.3c.1-.7.1-.7.2-1 .5-2.2 1-4.5 1.4-6.7.1-.2.1-.3.3-.3H18c-.2 1.2-.4 2.1-.7 3.2-.3 1.5-.6 3-1 4.5 0 .2-.1.2-.3.2M5 8.2c0-.1.2-.2.3-.2h3.4c.5 0 .9.3 1 .8l.9 4.4c0 .1 0 .1.1.2 0-.1.1-.1.1-.1l2.1-5.1c-.1-.1 0-.2.1-.2h2.1c0 .1 0 .1-.1.2l-3.1 7.3c-.1.2-.1.3-.2.4-.1.1-.3 0-.5 0H9.7c-.1 0-.2 0-.2-.2L7.9 9.5c-.2-.2-.5-.5-.9-.6-.6-.3-1.7-.5-1.9-.5L5 8.2z'
													fill='#142688'
												/>
											</svg>
										</div>
							
										<div className='payment-item'>
											<svg
												viewBox='0 0 38 24'
												xmlns='http://www.w3.org/2000/svg'
												role='img'
												width={38}
												height={24}
												aria-labelledby='pi-master'
											>
												<title id='pi-master'>
													Mastercard
												</title>
												<path
													opacity='.07'
													d='M35 0H3C1.3 0 0 1.3 0 3v18c0 1.7 1.4 3 3 3h32c1.7 0 3-1.3 3-3V3c0-1.7-1.4-3-3-3z'
												/>
												<path
													fill='#fff'
													d='M35 1c1.1 0 2 .9 2 2v18c0 1.1-.9 2-2 2H3c-1.1 0-2-.9-2-2V3c0-1.1.9-2 2-2h32'
												/>
												<circle
													fill='#EB001B'
													cx={15}
													cy={12}
													r={7}
												/>
												<circle
													fill='#F79E1B'
													cx={23}
													cy={12}
													r={7}
												/>
												<path
													fill='#FF5F00'
													d='M22 12c0-2.4-1.2-4.5-3-5.7-1.8 1.3-3 3.4-3 5.7s1.2 4.5 3 5.7c1.8-1.2 3-3.3 3-5.7z'
												/>
											</svg>
										</div>
						
									
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</section>
	);
}
