"use client";

import { createContext, useCallback, useContext, useEffect, useState } from "react";
import type { SerializedQuickAddItem } from "@/modules/_core";

type QuickAddState = {
  sheetOpen: boolean;
  paletteOpen: boolean;
  activeCreateKey: string | null;
  openSheet: () => void;
  closeSheet: () => void;
  openPalette: () => void;
  closePalette: () => void;
  openCreate: (key: string) => void;
  closeCreate: () => void;
  actions: SerializedQuickAddItem[];
};

const QuickAddContext = createContext<QuickAddState | null>(null);

export function useQuickAdd() {
  const ctx = useContext(QuickAddContext);
  if (!ctx) throw new Error("useQuickAdd must be used inside QuickAddProvider");
  return ctx;
}

export function QuickAddProvider({
  children,
  actions,
}: {
  children: React.ReactNode;
  actions: SerializedQuickAddItem[];
}) {
  const [sheetOpen, setSheetOpen] = useState(false);
  const [paletteOpen, setPaletteOpen] = useState(false);
  const [activeCreateKey, setActiveCreateKey] = useState<string | null>(null);

  const openSheet = useCallback(() => setSheetOpen(true), []);
  const closeSheet = useCallback(() => setSheetOpen(false), []);
  const openPalette = useCallback(() => setPaletteOpen(true), []);
  const closePalette = useCallback(() => setPaletteOpen(false), []);
  const openCreate = useCallback((key: string) => setActiveCreateKey(key), []);
  const closeCreate = useCallback(() => setActiveCreateKey(null), []);

  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        setPaletteOpen((prev) => !prev);
      }
    }
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, []);

  return (
    <QuickAddContext.Provider
      value={{
        sheetOpen,
        paletteOpen,
        activeCreateKey,
        openSheet,
        closeSheet,
        openPalette,
        closePalette,
        openCreate,
        closeCreate,
        actions,
      }}
    >
      {children}
    </QuickAddContext.Provider>
  );
}
