import React, { useState, useCallback, useRef, useEffect } from "react";

import {
  useShortcut,
  ShortcutScope,
  ShortcutHint,
  ShortcutManager,
} from "../components/Shortcuts";

import { Sidebar } from "../components/Sidebar";
import { routes, actionRoutes } from "../components/Sidebar/mock";
import { FilterPanel } from "../components/FilterPanel";
import { Modal } from "../components/Modal";
import { Notification } from "../components/Notification";

import SaveAsIcon from "@mui/icons-material/SaveAs";
import HomeIcon from "@mui/icons-material/Home";
import AppsIcon from "@mui/icons-material/Apps";
import AssessmentOutlinedIcon from "@mui/icons-material/AssessmentOutlined";
import SearchIcon from "@mui/icons-material/Search";
import KeyboardIcon from "@mui/icons-material/Keyboard";

export default {
  title: "Components/Shortcuts",
  tags: ["autodocs"],
  parameters: {
    layout: "fullscreen",
    docs: {
      description: {
        component:
          "Demonstrates how application teams integrate the keyboard shortcut system " +
          "with real Impact UI components — Sidebar, FilterPanel, Modal, and Notification.",
      },
    },
  },
};

// ---------------------------------------------------------------------------
// Filter panel config (reuses pattern from FilterPanel stories)
// ---------------------------------------------------------------------------

const filterOptions = [
  {
    id: 1,
    value: "merch-division",
    title: "Merch Division",
    icon: <SaveAsIcon />,
    required: false,
    numberOfFilter: 0,
    children: (
      <div style={{ padding: 16 }}>
        <p style={{ margin: 0, color: "#6b7280" }}>
          Select merch divisions to filter by.
        </p>
      </div>
    ),
  },
  {
    id: 2,
    value: "attributes",
    title: "Attributes",
    icon: <HomeIcon />,
    required: true,
    numberOfFilter: 3,
    children: (
      <div style={{ padding: 16 }}>
        <p style={{ margin: 0, color: "#6b7280" }}>
          Configure attribute filters.
        </p>
      </div>
    ),
  },
  {
    id: 3,
    value: "product-hierarchy",
    title: "Product Hierarchy",
    icon: <AppsIcon />,
    required: true,
    numberOfFilter: 0,
    children: (
      <div style={{ padding: 16 }}>
        <p style={{ margin: 0, color: "#6b7280" }}>
          Select product hierarchy levels.
        </p>
      </div>
    ),
  },
  {
    id: 4,
    value: "store-group",
    title: "Store Group",
    icon: <AssessmentOutlinedIcon />,
    required: false,
    numberOfFilter: 1,
    children: (
      <div style={{ padding: 16 }}>
        <p style={{ margin: 0, color: "#6b7280" }}>
          Choose store groups to include.
        </p>
      </div>
    ),
  },
];

// ---------------------------------------------------------------------------
// Sidebar module → shortcut key mapping
// ---------------------------------------------------------------------------

const MODULE_SHORTCUTS = [
  { key: "d", value: "des-dash", label: "Decision Dashboard" },
  { key: "m", value: "mark-cal", label: "Marketing Calendar" },
  { key: "r", value: "rules", label: "Rules" },
  { key: "p", value: "prod-det", label: "Product Details" },
];

// ---------------------------------------------------------------------------
// Story 1: Application Dashboard
// ---------------------------------------------------------------------------

export const ApplicationDashboard = {
  name: "Application Dashboard",
  render: () => <DashboardDemo />,
  parameters: {
    docs: {
      description: {
        story:
          "A mini application layout wired with keyboard shortcuts. " +
          "Use **Mod+S** (⌘S on Mac, Ctrl+S on Windows) to toggle the sidebar, **Alt+F** for filters, " +
          "**Alt+N** for notifications, **Mod+K** for search, and " +
          "**Ctrl+Shift+D/M/R/P** to navigate sidebar modules. " +
          "Press **Mod+Shift+/** to view the full shortcut reference.",
      },
    },
  },
};

function DashboardDemo() {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [filterOpen, setFilterOpen] = useState(false);
  const [filterActive, setFilterActive] = useState("merch-division");
  const [notifOpen, setNotifOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [helpOpen, setHelpOpen] = useState(false);
  const [activeModule, setActiveModule] = useState("des-dash");
  const [log, setLog] = useState([]);

  const addLog = useCallback(
    (msg) =>
      setLog((prev) => [
        ...prev.slice(-19),
        `${new Date().toLocaleTimeString()} — ${msg}`,
      ]),
    []
  );

  // --- Global shortcuts ---

  useShortcut("mod+s", () => {
    setSidebarOpen((v) => !v);
    addLog("Toggled sidebar");
  }, {
    id: "app-toggle-sidebar",
    description: "Toggle sidebar",
    preventDefault: true,
  });

  useShortcut("alt+f", () => {
    setFilterOpen((v) => !v);
    addLog("Toggled filter panel");
  }, {
    id: "app-toggle-filter",
    description: "Toggle filter panel",
  });

  useShortcut("alt+n", () => {
    setNotifOpen((v) => !v);
    addLog("Toggled notifications");
  }, {
    id: "app-toggle-notifications",
    description: "Toggle notification panel",
  });

  useShortcut("mod+k", () => {
    setSearchOpen(true);
    addLog("Opened search");
  }, {
    id: "app-open-search",
    description: "Open search",
  });

  useShortcut("escape", () => {
    if (filterOpen) {
      setFilterOpen(false);
      addLog("Closed filter panel (Esc)");
    } else if (notifOpen) {
      setNotifOpen(false);
      addLog("Closed notifications (Esc)");
    }
  }, {
    id: "app-global-escape",
    priority: 0,
    description: "Close open panel",
  });

  useShortcut("mod+shift+/", () => {
    setHelpOpen((v) => !v);
    addLog("Toggled shortcut reference");
  }, {
    id: "app-toggle-help",
    description: "Toggle shortcut reference",
  });

  return (
    <div style={{ display: "flex", height: "100vh", overflow: "hidden", fontFamily: "sans-serif" }}>
      {/* Sidebar */}
      <Sidebar
        isOpen={sidebarOpen}
        setIsOpen={setSidebarOpen}
        handleClose={() => setSidebarOpen((v) => !v)}
        routes={routes}
        actionRoutes={actionRoutes}
        parentActive={activeModule}
        handleParentRouteChange={(item) => {
          setActiveModule(item.value);
          addLog(`Navigated to ${item.label} (click)`);
        }}
        childActive=""
        handleChildRouteChange={() => {}}
        handleLogOut={() => addLog("Logout clicked")}
        isCloseWhenClickOutside={false}
        isMemoryRouter={false}
      />

      {/* Main content area */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        {/* Top bar */}
        <TopBar
          onSearchClick={() => { setSearchOpen(true); addLog("Opened search (click)"); }}
          activeModule={activeModule}
        />

        {/* Module navigation shortcuts */}
        <SidebarNavShortcuts
          setActiveModule={setActiveModule}
          setSidebarOpen={setSidebarOpen}
          addLog={addLog}
        />

        {/* Body */}
        <div style={{ flex: 1, overflow: "auto", padding: 24, backgroundColor: "#f9fafb" }}>
          <ActiveModuleContent activeModule={activeModule} />
        </div>

        {/* Event log */}
        <EventLog log={log} />

        {/* Help floating badge */}
        <div style={{
          position: "fixed",
          bottom: 56,
          right: 16,
          display: "flex",
          alignItems: "center",
          gap: 6,
          padding: "6px 12px",
          borderRadius: 20,
          backgroundColor: "#1e293b",
          color: "#e2e8f0",
          fontSize: 12,
          zIndex: 900,
          cursor: "pointer",
          boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
        }} onClick={() => setHelpOpen((v) => !v)}>
          <KeyboardIcon style={{ fontSize: 14 }} />
          <span>Shortcuts</span>
          <ShortcutHint
            keys="mod+shift+/"
            style={{
              color: "#cbd5e1",
              backgroundColor: "#334155",
              border: "1px solid #475569",
              fontSize: 10,
            }}
          />
        </div>
      </div>

      {/* FilterPanel overlay */}
      <FilterPanel
        title="Filter Panel"
        anchor="right"
        size="large"
        isOpen={filterOpen}
        setIsOpen={setFilterOpen}
        active={filterActive}
        setActive={setFilterActive}
        filters={filterOptions}
        handleClose={() => { setFilterOpen(false); addLog("Filter panel closed"); }}
        primaryButtonLabel="Apply"
        secondaryButtonLabel="Reset"
        onPrimaryButtonClick={() => { setFilterOpen(false); addLog("Filters applied"); }}
        onSecondaryButtonClick={() => addLog("Filters reset")}
      />

      {/* Notification overlay */}
      <Notification
        title="Notifications"
        isOpen={notifOpen}
        setIsOpen={setNotifOpen}
        handleClose={() => { setNotifOpen(false); addLog("Notifications closed"); }}
      />

      {/* Search modal with scoped escape */}
      {searchOpen && (
        <ShortcutScope name="modal-search" active>
          <SearchModal
            onClose={() => { setSearchOpen(false); addLog("Search closed"); }}
          />
        </ShortcutScope>
      )}

      {/* Shortcut help overlay */}
      {helpOpen && (
        <ShortcutHelpOverlay onClose={() => setHelpOpen(false)} />
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Sidebar navigation shortcut registrations
// ---------------------------------------------------------------------------

function SidebarNavShortcuts({ setActiveModule, setSidebarOpen, addLog }) {
  useShortcut("ctrl+shift+d", () => {
    setActiveModule("des-dash");
    setSidebarOpen(true);
    addLog("Navigated to Decision Dashboard (Ctrl+Shift+D)");
  }, { id: "app-nav-des-dash", description: "Navigate to Decision Dashboard" });

  useShortcut("ctrl+shift+m", () => {
    setActiveModule("mark-cal");
    setSidebarOpen(true);
    addLog("Navigated to Marketing Calendar (Ctrl+Shift+M)");
  }, { id: "app-nav-mark-cal", description: "Navigate to Marketing Calendar" });

  useShortcut("ctrl+shift+r", () => {
    setActiveModule("rules");
    setSidebarOpen(true);
    addLog("Navigated to Rules (Ctrl+Shift+R)");
  }, { id: "app-nav-rules", description: "Navigate to Rules" });

  useShortcut("ctrl+shift+p", () => {
    setActiveModule("prod-det");
    setSidebarOpen(true);
    addLog("Navigated to Product Details (Ctrl+Shift+P)");
  }, { id: "app-nav-prod-det", description: "Navigate to Product Details" });

  return null;
}

// ---------------------------------------------------------------------------
// Top bar
// ---------------------------------------------------------------------------

function TopBar({ onSearchClick, activeModule }) {
  const moduleLabel = routes.find((r) => r.value === activeModule)?.label || activeModule;

  return (
    <div style={{
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      padding: "12px 24px",
      borderBottom: "1px solid #e5e7eb",
      backgroundColor: "#fff",
    }}>
      <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{moduleLabel}</h2>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <button onClick={onSearchClick} style={topBarBtnStyle}>
          <SearchIcon style={{ fontSize: 16, marginRight: 6 }} />
          Search
          <ShortcutHint keys="mod+k" style={{ marginLeft: 8, fontSize: 10 }} />
        </button>
        <ActionPill label="Filters" shortcut="alt+f" />
        <ActionPill label="Notifications" shortcut="alt+n" />
        <ActionPill label="Sidebar" shortcut="mod+s" />
      </div>
    </div>
  );
}

function ActionPill({ label, shortcut }) {
  return (
    <span style={{
      display: "inline-flex",
      alignItems: "center",
      gap: 4,
      fontSize: 12,
      color: "#6b7280",
    }}>
      {label}
      <ShortcutHint keys={shortcut} style={{ fontSize: 10 }} />
    </span>
  );
}

// ---------------------------------------------------------------------------
// Active module content
// ---------------------------------------------------------------------------

function ActiveModuleContent({ activeModule }) {
  const mod = routes.find((r) => r.value === activeModule);
  const label = mod?.label || activeModule;

  return (
    <div>
      <div style={{
        padding: 32,
        borderRadius: 12,
        backgroundColor: "#fff",
        border: "1px solid #e5e7eb",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 40, marginBottom: 12 }}>{mod?.icon}</div>
        <h3 style={{ margin: "0 0 8px", fontSize: 20 }}>{label}</h3>
        <p style={{ margin: 0, color: "#9ca3af", maxWidth: 480, marginInline: "auto" }}>
          This is the <strong>{label}</strong> module. Use sidebar navigation shortcuts
          to switch between modules.
        </p>

        <div style={{
          marginTop: 24,
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "center",
          gap: 8,
        }}>
          {MODULE_SHORTCUTS.map(({ key, label: navLabel }) => (
            <span key={key} style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
              padding: "4px 10px",
              borderRadius: 6,
              backgroundColor: "#f3f4f6",
              fontSize: 12,
              color: "#374151",
            }}>
              <ShortcutHint keys={`ctrl+shift+${key}`} style={{ fontSize: 10 }} />
              {navLabel}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Search modal
// ---------------------------------------------------------------------------

function SearchModal({ onClose }) {
  const inputRef = useRef(null);

  useShortcut("escape", onClose, {
    id: "app-search-escape",
    scope: "modal-search",
    priority: 10,
    description: "Close search modal",
  });

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  return (
    <Modal
      open
      onClose={onClose}
      title="Search"
      width={520}
    >
      <div style={{ padding: "0 0 8px" }}>
        <input
          ref={inputRef}
          type="text"
          placeholder="Type to search..."
          style={{
            width: "100%",
            padding: "10px 14px",
            borderRadius: 8,
            border: "1px solid #d1d5db",
            fontSize: 14,
            outline: "none",
            boxSizing: "border-box",
          }}
        />
        <p style={{ margin: "12px 0 0", fontSize: 12, color: "#9ca3af" }}>
          Press <ShortcutHint keys="escape" style={{ fontSize: 10 }} /> to close.
          Notice that typing here does NOT trigger other shortcuts (input safety).
        </p>
      </div>
    </Modal>
  );
}

// ---------------------------------------------------------------------------
// Shortcut help overlay
// ---------------------------------------------------------------------------

function ShortcutHelpOverlay({ onClose }) {
  const allShortcuts = ShortcutManager.getInstance().getAllShortcuts();

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        backgroundColor: "rgba(0,0,0,0.5)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 2000,
      }}
      onClick={onClose}
    >
      <div
        style={{
          backgroundColor: "#fff",
          borderRadius: 12,
          padding: 24,
          maxWidth: 560,
          width: "90%",
          maxHeight: "80vh",
          overflow: "auto",
          boxShadow: "0 20px 60px rgba(0,0,0,0.2)",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <h3 style={{ margin: 0, fontSize: 18 }}>Keyboard Shortcuts</h3>
          <button onClick={onClose} style={{ border: "none", background: "none", cursor: "pointer", fontSize: 18, color: "#6b7280" }}>
            &times;
          </button>
        </div>
        <ShortcutTable shortcuts={allShortcuts} />
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Event log bar
// ---------------------------------------------------------------------------

function EventLog({ log }) {
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [log]);

  return (
    <div style={{
      height: 44,
      borderTop: "1px solid #e5e7eb",
      backgroundColor: "#1e293b",
      color: "#94a3b8",
      fontSize: 12,
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      padding: "0 16px",
      overflow: "hidden",
    }}>
      <span style={{ color: "#64748b", marginRight: 8, flexShrink: 0 }}>LOG</span>
      <div ref={scrollRef} style={{ overflow: "auto", whiteSpace: "nowrap", flex: 1 }}>
        {log.length === 0
          ? "Press a shortcut to see events here..."
          : log[log.length - 1]}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Story 2: Shortcut Reference
// ---------------------------------------------------------------------------

export const ShortcutReference = {
  name: "Shortcut Reference",
  render: () => <ShortcutReferenceDemo />,
  parameters: {
    docs: {
      description: {
        story:
          "A live reference of all registered keyboard shortcuts. " +
          "Application teams can use `ShortcutManager.getAllShortcuts()` " +
          "to build help panels like this.",
      },
    },
  },
};

function ShortcutReferenceDemo() {
  const [shortcuts, setShortcuts] = useState([]);

  // Register some example shortcuts to populate the table
  useShortcut("mod+s", () => {}, { id: "ref-toggle-sidebar", description: "Toggle sidebar" });
  useShortcut("alt+f", () => {}, { id: "ref-toggle-filter", description: "Toggle filter panel" });
  useShortcut("alt+n", () => {}, { id: "ref-toggle-notif", description: "Toggle notifications" });
  useShortcut("mod+k", () => {}, { id: "ref-open-search", description: "Open search" });
  useShortcut("ctrl+shift+d", () => {}, { id: "ref-nav-dashboard", description: "Navigate to Decision Dashboard" });
  useShortcut("ctrl+shift+m", () => {}, { id: "ref-nav-marketing", description: "Navigate to Marketing Calendar" });
  useShortcut("ctrl+shift+r", () => {}, { id: "ref-nav-rules", description: "Navigate to Rules" });
  useShortcut("ctrl+shift+p", () => {}, { id: "ref-nav-products", description: "Navigate to Product Details" });
  useShortcut("mod+shift+/", () => {}, { id: "ref-toggle-help", description: "Toggle shortcut reference" });
  useShortcut("escape", () => {}, { id: "ref-close-panel", description: "Close open panel" });

  useEffect(() => {
    setShortcuts(ShortcutManager.getInstance().getAllShortcuts());
  }, []);

  return (
    <div style={{ maxWidth: 680, margin: "40px auto", fontFamily: "sans-serif", padding: "0 16px" }}>
      <h2 style={{ margin: "0 0 4px" }}>Keyboard Shortcuts</h2>
      <p style={{ margin: "0 0 24px", color: "#6b7280" }}>
        All shortcuts registered by the application, pulled from{" "}
        <code>ShortcutManager.getAllShortcuts()</code>.
      </p>
      <ShortcutTable shortcuts={shortcuts} />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Shared: shortcut table
// ---------------------------------------------------------------------------

function ShortcutTable({ shortcuts }) {
  if (!shortcuts.length) {
    return <p style={{ color: "#9ca3af" }}>No shortcuts registered.</p>;
  }

  const grouped = shortcuts.reduce((acc, s) => {
    const scope = s.scope || "global";
    if (!acc[scope]) acc[scope] = [];
    acc[scope].push(s);
    return acc;
  }, {});

  return (
    <div>
      {Object.entries(grouped).map(([scope, items]) => (
        <div key={scope} style={{ marginBottom: 20 }}>
          <h4 style={{
            margin: "0 0 8px",
            fontSize: 11,
            textTransform: "uppercase",
            letterSpacing: "0.05em",
            color: "#9ca3af",
          }}>
            {scope} scope
          </h4>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <tbody>
              {items.map((s) => (
                <tr key={s.id}>
                  <td style={refTdLeft}>
                    <ShortcutHint keys={s.keys} />
                  </td>
                  <td style={refTdRight}>
                    {s.description || <span style={{ color: "#d1d5db" }}>--</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Shared styles
// ---------------------------------------------------------------------------

const topBarBtnStyle = {
  display: "inline-flex",
  alignItems: "center",
  padding: "6px 14px",
  borderRadius: 8,
  border: "1px solid #e5e7eb",
  backgroundColor: "#f9fafb",
  cursor: "pointer",
  fontSize: 13,
  color: "#374151",
};

const refTdLeft = {
  padding: "8px 12px 8px 0",
  borderBottom: "1px solid #f3f4f6",
  width: 160,
};

const refTdRight = {
  padding: "8px 0",
  borderBottom: "1px solid #f3f4f6",
  fontSize: 13,
  color: "#374151",
};
