"use client";

import Link from "next/link";
import { useEffect, useState, useCallback } from "react";
import { getCart, saveCart, cartCount, cartSubtotal, money, lineTotal, type CartItem } from "@/lib/cart";

export default function CartDrawer() {
  const [open, setOpen] = useState(false);
  const [cart, setCart] = useState<CartItem[]>([]);

  const refresh = useCallback(() => setCart(getCart()), []);

  useEffect(() => {
    refresh();
    const onChange = () => refresh();
    const onOpenClick = (e: MouseEvent) => {
      const t = e.target as HTMLElement;
      if (t.closest("[data-cart-open]")) {
        e.preventDefault();
        refresh();
        setOpen(true);
      }
    };
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("awafi-cart-change", onChange);
    window.addEventListener("storage", onChange);
    document.addEventListener("click", onOpenClick);
    document.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("awafi-cart-change", onChange);
      window.removeEventListener("storage", onChange);
      document.removeEventListener("click", onOpenClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [refresh]);

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const mutate = (next: CartItem[]) => { saveCart(next); setCart(next); };
  const changeQty = (id: string, delta: number) =>
    mutate(cart.map((i) => (i.id === id ? { ...i, qty: Math.max(i.minOrder || 1, i.qty + delta) } : i)));
  const remove = (id: string) => mutate(cart.filter((i) => i.id !== id));

  const count = cartCount(cart);
  const subtotal = cartSubtotal(cart);

  return (
    <div className={`pb-cart-drawer${open ? " is-open" : ""}`} aria-hidden={!open}>
      <div className="pb-cart-scrim" onClick={() => setOpen(false)} />
      <aside className="pb-cart-panel" role="dialog" aria-label="Shopping cart" aria-modal="true">
        <header className="pb-cart-head">
          <h3>Your cart <span className="pb-cart-headcount">({count})</span></h3>
          <button className="pb-cart-x" onClick={() => setOpen(false)} aria-label="Close cart">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="m6 6 12 12M18 6 6 18" strokeLinecap="round" /></svg>
          </button>
        </header>

        {cart.length > 0 && (
          <div className="pb-cart-body" id="pbCartBody">
            {cart.map((i) => (
              <div className="pb-ci" key={i.id}>
                <div className="pb-ci-img">{/* eslint-disable-next-line @next/next/no-img-element */}<img src={i.image} alt="" /></div>
                <div className="pb-ci-info">
                  <span className="pb-ci-brand">{i.brand}</span>
                  <Link className="pb-ci-name" href={`/portal/product/${i.id}`} onClick={() => setOpen(false)}>{i.name}</Link>
                  <div className="pb-ci-row">
                    <div className="pb-ci-qty">
                      <button onClick={() => changeQty(i.id, -1)} aria-label="Decrease">−</button>
                      <span>{i.qty}</span>
                      <button onClick={() => changeQty(i.id, 1)} aria-label="Increase">+</button>
                    </div>
                    <button className="pb-ci-remove" onClick={() => remove(i.id)}>Remove</button>
                  </div>
                </div>
                <div className="pb-ci-price">{money(lineTotal(i))}</div>
              </div>
            ))}
          </div>
        )}

        {cart.length === 0 && (
          <div className="pb-cart-empty" id="pbCartEmpty">
            <svg viewBox="0 0 24 24" width="46" height="46" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M4 6h16l-1.4 10.5a2 2 0 0 1-2 1.7H7.4a2 2 0 0 1-2-1.7L4 6Z" /><path d="M9 6a3 3 0 0 1 6 0" strokeLinecap="round" /></svg>
            <p>Your cart is empty</p>
            <button className="pb-btn pb-btn--ghost" onClick={() => setOpen(false)}>Continue shopping</button>
          </div>
        )}

        {cart.length > 0 && (
          <footer className="pb-cart-foot" id="pbCartFoot">
            <div className="pb-cart-line"><span>Subtotal</span><strong>{money(subtotal)}</strong></div>
            <p className="pb-cart-note">VAT &amp; delivery calculated at checkout · trade prices excl. VAT.</p>
            <Link href="/portal/checkout" className="pb-btn pb-btn--primary pb-btn--lg" onClick={() => setOpen(false)}>Proceed to checkout</Link>
          </footer>
        )}
      </aside>
    </div>
  );
}
