"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import TiltCard from "@/components/motion/TiltCard";
import { shopItems, shopCategories } from "@/lib/content/shop";

const fmt = (n: number) => (n === 0 ? "Free" : `SAR ${n.toLocaleString()}`);

export default function ShopClient() {
  const router = useRouter();
  const reduced = useReducedMotion();
  const [cat, setCat] = useState<string>("All");
  const [cart, setCart] = useState<Record<string, number>>({});
  const [open, setOpen] = useState(false);

  const visible = shopItems.filter((i) => cat === "All" || i.category === cat);
  const lines = Object.entries(cart).filter(([, q]) => q > 0);
  const count = lines.reduce((a, [, q]) => a + q, 0);
  const total = useMemo(
    () => lines.reduce((a, [slug, q]) => a + (shopItems.find((i) => i.slug === slug)?.priceSar ?? 0) * q, 0),
    [lines]
  );

  const add = (slug: string) => setCart((c) => ({ ...c, [slug]: (c[slug] ?? 0) + 1 }));
  const dec = (slug: string) => setCart((c) => ({ ...c, [slug]: Math.max(0, (c[slug] ?? 0) - 1) }));

  const checkout = () => {
    const summary = lines
      .map(([slug, q]) => {
        const it = shopItems.find((i) => i.slug === slug)!;
        return `${q}× ${it.name} — ${fmt(it.priceSar)}`;
      })
      .join("\n");
    const msg = `Shop order request:\n${summary}\n\nEstimated total: ${fmt(total)} (VAT incl.)`;
    router.push(`/contact?topic=shop&item=${encodeURIComponent(msg)}`);
  };

  return (
    <>
      {/* filters */}
      <div role="group" aria-label="Filter shop" className="flex flex-wrap gap-2.5">
        {shopCategories.map((c) => {
          const active = cat === c;
          return (
            <button
              key={c}
              onClick={() => setCat(c)}
              aria-pressed={active}
              className={`rounded-full border px-4 py-2 font-[family-name:var(--font-mono)] text-[0.8rem] tracking-[0.08em] transition-all ${
                active
                  ? "border-azure-deep bg-azure-deep font-medium text-white"
                  : "border-black/15 text-lmid hover:border-azure-deep hover:text-azure-deep"
              }`}
            >
              {c}
            </button>
          );
        })}
      </div>

      {/* grid */}
      <motion.div layout={!reduced} className="mt-10 grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3">
        <AnimatePresence mode="popLayout">
          {visible.map((it) => {
            const qty = cart[it.slug] ?? 0;
            return (
              <motion.div
                key={it.slug}
                layout={!reduced}
                initial={reduced ? false : { opacity: 0, y: 14, scale: 0.985 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={reduced ? undefined : { opacity: 0, scale: 0.985 }}
                transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}
                className="h-full"
              >
                <TiltCard className="h-full" max={4}>
                  <div className="notch-card flex h-full flex-col rounded-xl border border-black/10 bg-white p-6">
                    <div className="flex items-start justify-between gap-3">
                      <span className="font-[family-name:var(--font-mono)] text-[0.66rem] uppercase tracking-[0.14em] text-llo">
                        {it.category}
                      </span>
                      {it.popular && (
                        <span className="rounded-full bg-azure/10 px-2.5 py-0.5 font-[family-name:var(--font-mono)] text-[0.62rem] uppercase tracking-[0.1em] text-azure-deep">
                          Popular
                        </span>
                      )}
                    </div>
                    <h3 className="mt-3 text-[1.12rem] font-semibold text-lhi">{it.name}</h3>
                    <p className="mt-2 flex-1 text-[0.9rem] leading-relaxed text-lmid">{it.blurb}</p>
                    <div className="mt-4 flex items-end justify-between border-t border-dashed border-black/10 pt-4">
                      <div>
                        <div className="font-[family-name:var(--font-mono)] text-lg font-medium text-azure-deep tnum">
                          {fmt(it.priceSar)}
                        </div>
                        <div className="mt-0.5 text-[0.72rem] text-llo">Delivery: {it.eta}</div>
                      </div>
                      {qty === 0 ? (
                        <button onClick={() => add(it.slug)} className="btn btn-ghost-light btn-sm">
                          Add
                        </button>
                      ) : (
                        <div className="flex items-center gap-2.5 rounded-lg border border-azure-deep/30 px-2 py-1">
                          <button onClick={() => dec(it.slug)} aria-label={`Remove one ${it.name}`} className="grid h-6 w-6 place-items-center text-azure-deep hover:bg-azure/10">
                            −
                          </button>
                          <span className="min-w-4 text-center font-[family-name:var(--font-mono)] text-sm text-lhi tnum">{qty}</span>
                          <button onClick={() => add(it.slug)} aria-label={`Add one ${it.name}`} className="grid h-6 w-6 place-items-center text-azure-deep hover:bg-azure/10">
                            +
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                </TiltCard>
              </motion.div>
            );
          })}
        </AnimatePresence>
      </motion.div>

      {/* floating cart */}
      <AnimatePresence>
        {count > 0 && (
          <motion.div
            initial={reduced ? false : { y: 80, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={reduced ? undefined : { y: 80, opacity: 0 }}
            transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}
            className="fixed inset-x-0 bottom-0 z-[120] px-4 pb-4"
          >
            <div className="mx-auto flex w-full max-w-[680px] flex-wrap items-center justify-between gap-4 rounded-2xl border border-white/15 bg-ink-2/95 p-4 shadow-[0_20px_60px_-20px_rgba(0,0,0,0.7)] backdrop-blur-xl">
              <button
                onClick={() => setOpen((o) => !o)}
                className="flex items-center gap-3 text-left"
                aria-expanded={open}
              >
                <span className="grid h-10 w-10 place-items-center rounded-full bg-azure text-[#04122B] font-[family-name:var(--font-mono)] text-sm font-bold tnum">
                  {count}
                </span>
                <span>
                  <span className="block text-[0.82rem] text-tmid">Estimated total</span>
                  <span className="block font-[family-name:var(--font-mono)] text-lg font-medium text-thi tnum">
                    {fmt(total)}
                  </span>
                </span>
                <span className="ml-1 text-tlo">{open ? "▾" : "▴"}</span>
              </button>
              <div className="flex gap-2">
                <button onClick={() => setCart({})} className="btn btn-ghost-dark btn-sm">
                  Clear
                </button>
                <button onClick={checkout} className="btn btn-primary btn-sm">
                  Request order <span className="arrow" aria-hidden>→</span>
                </button>
              </div>

              {open && (
                <div className="w-full border-t border-white/10 pt-3">
                  <ul className="grid max-h-[40vh] gap-2 overflow-y-auto thin-scroll">
                    {lines.map(([slug, q]) => {
                      const it = shopItems.find((i) => i.slug === slug)!;
                      return (
                        <li key={slug} className="flex items-center justify-between gap-3 text-[0.85rem]">
                          <span className="text-tmid">
                            <span className="font-[family-name:var(--font-mono)] text-tlo tnum">{q}×</span> {it.name}
                          </span>
                          <span className="font-[family-name:var(--font-mono)] text-thi tnum">{fmt(it.priceSar * q)}</span>
                        </li>
                      );
                    })}
                  </ul>
                  <p className="mt-3 text-[0.75rem] text-tlo">
                    This sends your selection to our team as an order request — no payment is taken here.
                  </p>
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
