"use client";

import Link from "next/link";
import { ArrowLeft, Minus, PackageOpen, Plus, ShoppingBag, Trash2 } from "lucide-react";
import { useEffect } from "react";
import { usePreferences } from "@/components/providers/app-providers";
import { useStore } from "./store-provider";
import type { StoreProduct } from "./store-types";

export function CartPage({ products }: { products: StoreProduct[] }) {
  const { dictionary: t, locale } = usePreferences();
  const { items, hydrated, href, removeItem, setQuantity } = useStore();
  const productMap = new Map(products.map((product) => [product.sku, product]));
  const lines = Object.entries(items).flatMap(([sku, quantity]) => {
    const product = productMap.get(sku);
    return product ? [{ product, quantity }] : [];
  });
  const subtotal = lines.reduce((total, line) => total + Number(line.product.price) * line.quantity, 0);

  useEffect(() => {
    for (const [sku] of Object.entries(items)) {
      if (!productMap.has(sku)) removeItem(sku);
    }
  }, [items, productMap, removeItem]);

  const money = (value: number) => `${new Intl.NumberFormat(locale === "ar" ? "ar-EG" : "en-EG", { maximumFractionDigits: 2 }).format(value)} ${t.store.catalog.currency}`;

  if (!hydrated) return <section className="store-page"><div className="store-loading" /></section>;
  if (lines.length === 0) {
    return (
      <section className="store-page store-empty-page">
        <div className="store-empty-icon"><ShoppingBag size={38} /></div>
        <h1>{t.store.cart.empty}</h1>
        <p>{t.store.cart.emptyDescription}</p>
        <Link className="store-primary-action" href={`${href()}#products`}>{t.store.cart.continueShopping}</Link>
      </section>
    );
  }

  return (
    <section className="store-page">
      <div className="store-page-heading">
        <span><ShoppingBag size={20} /></span>
        <div><h1>{t.store.cart.title}</h1><p>{t.store.cart.description}</p></div>
      </div>
      <div className="store-cart-layout">
        <div className="store-cart-lines">
          {lines.map(({ product, quantity }) => {
            const safeMaximum = Math.max(1, Math.min(20, product.available));
            return (
              <article className="store-cart-line" key={product.sku}>
                <span className="store-cart-art"><PackageOpen size={30} /></span>
                <div className="store-cart-product">
                  <h2>{locale === "ar" ? product.nameAr : product.nameEn}</h2>
                  <span className="mono" dir="ltr">{product.sku}</span>
                  <strong><bdi dir="ltr">{money(Number(product.price))}</bdi></strong>
                </div>
                <div className="store-quantity" aria-label={t.store.cart.quantity}>
                  <button onClick={() => setQuantity(product.sku, quantity - 1)} type="button"><Minus size={15} /></button>
                  <bdi dir="ltr">{quantity}</bdi>
                  <button disabled={quantity >= safeMaximum} onClick={() => setQuantity(product.sku, quantity + 1)} type="button"><Plus size={15} /></button>
                </div>
                <strong className="store-line-total"><bdi dir="ltr">{money(Number(product.price) * quantity)}</bdi></strong>
                <button className="store-remove" onClick={() => removeItem(product.sku)} type="button" aria-label={t.store.cart.remove}>
                  <Trash2 size={18} />
                </button>
              </article>
            );
          })}
        </div>
        <aside className="store-summary-card">
          <h2>{t.store.checkout.summary}</h2>
          <div><span>{t.store.cart.subtotal}</span><strong><bdi dir="ltr">{money(subtotal)}</bdi></strong></div>
          <div><span>{t.store.cart.shipping}</span><strong>{t.store.cart.shippingValue}</strong></div>
          <div className="store-summary-total"><span>{t.store.cart.total}</span><strong><bdi dir="ltr">{money(subtotal)}</bdi></strong></div>
          <Link className="store-primary-action full" href={href("/checkout")}>
            {t.store.cart.checkout}<ArrowLeft className="rtl-arrow" size={18} />
          </Link>
          <Link className="store-text-link" href={`${href()}#products`}>{t.store.cart.continueShopping}</Link>
        </aside>
      </div>
    </section>
  );
}
