"use client";

import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Sparkles, X } from "lucide-react";
import { useQuickAdd } from "./quick-add-provider";
import { NavIcon } from "./nav-icon";
import type { SerializedQuickAddItem } from "@/modules/_core";

function groupByModule(
  actions: SerializedQuickAddItem[],
): Map<string, { name: string; items: SerializedQuickAddItem[] }> {
  const map = new Map<string, { name: string; items: SerializedQuickAddItem[] }>();
  for (const action of actions) {
    if (!map.has(action.moduleId)) {
      map.set(action.moduleId, { name: action.moduleName, items: [] });
    }
    map.get(action.moduleId)!.items.push(action);
  }
  return map;
}

const QUICK_ADD_ICON: Record<string, string> = {
  "calendar-plus": "calendar",
  "calendar-days": "calendar",
  "shopping-cart": "cart",
  "list-checks": "check-square",
  "list-plus": "list",
  "file-plus": "note",
};

export function QuickAddSheet() {
  const { sheetOpen, closeSheet, actions } = useQuickAdd();
  const router = useRouter();
  const backdropRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!sheetOpen) return;
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") closeSheet();
    }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [sheetOpen, closeSheet]);

  if (!sheetOpen) return null;

  const groups = groupByModule(actions);

  function handleAction(url: string) {
    closeSheet();
    router.push(url);
  }

  return (
    <>
      <div
        ref={backdropRef}
        className="fixed inset-0 z-40"
        style={{ background: "rgba(31,27,22,.32)", backdropFilter: "blur(2px)" }}
        onClick={closeSheet}
        aria-hidden="true"
      />

      <div
        role="dialog"
        aria-modal="true"
        aria-label="Quick add"
        className="fixed bottom-0 left-0 right-0 z-50 sm:bottom-auto sm:left-1/2 sm:top-24 sm:-translate-x-1/2 sm:w-[480px] sm:max-w-[calc(100vw-32px)]"
        style={{
          background: "var(--paper)",
          borderRadius: "18px 18px 0 0",
          boxShadow: "0 -8px 32px rgba(31,27,22,.16)",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            padding: "16px 18px 12px",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            borderBottom: "0.5px solid var(--hair)",
          }}
        >
          <h2
            className="serif"
            style={{ fontSize: 18, fontWeight: 500, margin: 0, color: "var(--ink)" }}
          >
            Quick add
          </h2>
          <button
            onClick={closeSheet}
            aria-label="Close quick add"
            className="btn btn-icon btn-ghost btn-sm"
          >
            <X className="size-3.5" />
          </button>
        </div>

        <div style={{ padding: "14px 18px" }}>
          <div
            className="muted"
            style={{
              fontSize: 12,
              marginBottom: 14,
              display: "flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            <Sparkles className="size-3" />
            <span>Pick what to add — or use ⌘K to search.</span>
          </div>

          <div className="max-h-[60vh] overflow-y-auto">
            {[...groups.entries()].map(([moduleId, group], i) => (
              <div key={moduleId} className="mb-2.5">
                <div className="eyebrow mb-2" style={{ marginTop: i === 0 ? 0 : 8 }}>
                  {group.name}
                </div>
                <div className="grid grid-cols-2 gap-1.5">
                  {group.items.map((action) => (
                    <button
                      key={action.id}
                      onClick={() => handleAction(action.url)}
                      className="btn btn-sm justify-start"
                    >
                      <NavIcon
                        name={QUICK_ADD_ICON[action.icon ?? ""] ?? "plus"}
                        className="size-3.5"
                      />
                      <span className="truncate">{action.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div
          className="dialog-foot"
          style={{
            padding: "12px 18px",
            display: "flex",
            gap: 8,
            justifyContent: "flex-end",
            borderTop: "0.5px solid var(--hair)",
            background: "var(--paper-2)",
          }}
        >
          <button className="btn btn-sm btn-ghost" onClick={closeSheet}>
            Close
          </button>
        </div>
      </div>
    </>
  );
}
