"use client";
import { useContextElement } from "@/context/Context";
import { useState, useEffect } from 'react'; 
import { useRouter } from 'next/navigation'; 

import Image from "next/image";
import Link from "next/link";

import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import { ShieldCheck } from 'lucide-react'; 

import { getProductCoin, getProductLanguage, getProductPrice, useT, getRONtoEURRate } from "@/context/I18nContext"; 

export default function Cart() {
     const router = useRouter(); 
	const { cartProducts, setCartProducts } = useContextElement();
	
     const [cartItems, setCartItems] = useState([]);
     const [totalPrice, setTotalPrice] = useState(0); 
     
     const [isChecked, setIsChecked] = useState(false); 

     const { t } = useT(); 

     const isEN = t("variable_categorii") != 'name';
     const [eurRate, setEurRate] = useState(null);

     useEffect(() => {
          if (isEN) getRONtoEURRate().then(setEurRate);
     }, [isEN]);

     const convertPrice = (price) => {
          if (isEN && eurRate) return (Math.ceil(price * eurRate) - 0.01).toFixed(2);
          return parseFloat(price).toFixed(2);
     }; 

     useEffect(() => {
          if (cartProducts && cartProducts.length > 0) {
               const validIds = cartProducts
                    .map(item => item.id)
                    .filter(id => /^\d+$/.test(id));

               if (validIds.length > 0) {
                    fetch(`/api/productsdatabyids?ids=${validIds.join(",")}`)
                         .then((res) => res.json())
                         .then((data) => {
                              setCartItems(data.wishlistProducts);

                              // Calculăm prețul total luând în considerare priceReduced dacă există
                              const newTotalPrice = data.wishlistProducts.reduce((sum, product) => {
                                   const cartItem = cartProducts.find(item => item.id == product.id);
                                   const quantity = cartItem ? cartItem.quantity : 0;
                                   
                                   const price = product.priceReduced && parseFloat(product.priceReduced) < parseFloat(product.price)
                                        ? parseFloat(product.priceReduced)
                                        : parseFloat(product.price);
                                   
                                   return sum + (price * quantity);
                              }, 0);

                              setTotalPrice(newTotalPrice + 22);
                         })
                         .catch((err) => console.error("Error fetching products:", err));
               } else {
                    setCartItems([]);
                    setTotalPrice(0);
               }
          } else {
               setCartItems([]);
               setTotalPrice(0);
          }
     }, [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)]);
     };

     const handleCheckboxChange = (e) => {
          setIsChecked(e.target.checked); 
     };

     const handleCheckoutClick = (e) => {
          e.preventDefault(); 
          if (!isChecked) {
               toast.warning("Trebuie să accepți termenii și condițiile înainte de a continua.");
               return;
          }
          router.push("/checkout"); 
     };

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

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

	return (
		<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;
                         border-radius: 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='tf-page-cart-wrap'>
					<div className='tf-page-cart-item'>
						<form onSubmit={(e) => e.preventDefault()}>
							<table className='tf-table-page-cart'>
								<thead>
									<tr>
										<th>{t("shopping_cart_product")}</th>
										<th>{t("shopping_cart_price")}</th>
										<th>{t("shopping_cart_quantity")}</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'
													>
										
                                                                      {getProductLanguage(elm)}
                                                                      {isReduced(elm) && (
                                                                           <span className='discount-badge'>
                                                                                🔥 Reducere
                                                                           </span>
                                                                      )}
													</Link>

													<span
														className='remove-cart link remove'
														onClick={() => removeItem(elm.id)}
													>
														{t("shopping_cart_delete")}
													</span>
												</div>
											</td>
											<td
												className='tf-cart-item_price'
												cart-data-title='Price'
											>
												<div className='cart-price'>
                                                                 {isReduced(elm) ? (
                                                                      <div className='price-wrapper'>
                                                                           <span className='price-original'>
                                                                                {convertPrice(parseFloat(elm.price).toFixed(2))} {getProductCoin()}
                                                                           </span>
                                                                           <span className='price-reduced'>
                                                                                {convertPrice(parseFloat(elm.priceReduced).toFixed(2))} {getProductCoin()}
                                                                           </span>
                                                                      </div>
                                                                 ) : (
                                                                      <span>{convertPrice(elm.price)} {getProductCoin()}</span>
                                                                 )}
												</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(p => p.id === elm.id)?.quantity || 1) - 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(p => p.id === elm.id)?.quantity || 1
                                                            }
															min={1}
															onChange={(e) =>
                                                                 setQuantity(
                                                                      elm.id,
                                                                      parseInt(e.target.value) || 1
                                                                 )
                                                            }
														/>
														<span
															className='btn-quantity plus-btn'
															onClick={() => setQuantity(
                                                                 elm.id,
                                                                 (cartProducts.find(p => p.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",
													}}
												>
                                                            {convertPrice((getFinalPrice(elm) * (cartProducts.find(p => p.id === elm.id)?.quantity || 1)).toFixed(2))} {getProductCoin()}
												</div>
											</td>
										</tr>
									))}
								</tbody>
							</table>
							{!cartProducts.length && (
								<>
									<div className='row align-items-center mb-5'>
										<div className='col-6 fs-18'>
                                                       {t("shopping_cart_empty")}
										</div>
										<div className='col-6'>
											<Link
												href={`/toate-produsele`}
												className='tf-btn btn-fill animate-hover-btn radius-3 w-100 justify-content-center'
												style={{
													width: "fit-content",
												}}
											>
												{t("shopping_cart_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>{t("shopping_cart_transport")}</h3>
									<span className='total-value'>
										{convertPrice("22")} {getProductCoin()}
									</span>
								</div>

								<div className='tf-cart-totals-discounts'>
									<h3>Subtotal</h3>
									<span className='total-value'>
										{convertPrice(totalPrice.toFixed(2))} {getProductCoin()}<br/>
                                                  <small style={{fontSize: 10}}>{t("shopping_cart_included")}</small>
									</span>
                                             
								</div>
				
								<div className='cart-checkbox'>
									<input
										type='checkbox'
										className='tf-check'
										id='check-agree'
                                                  checked={isChecked}
                                                  onChange={handleCheckboxChange}
									/>
									<label
										htmlFor='check-agree'
										className='fw-4'
									>
										{t("sunt_de_acord")}  <Link href={`/termeni-si-conditii`}>{t("termeni_si_conditii")}</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'
                                                  onClick={handleCheckoutClick}
									>
										<span>{t("shopping_cart_button")}</span>
									</Link>
								</div>
								<div className='tf-page-cart_imgtrust'>
									<p className='text-center fw-6'>
                                                  <ShieldCheck /> {t("shopping_cart_secured_payment")} <Link href="https://netopia-payments.com/">Netopia Payments</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>
	);
}