import { customElement, noShadowDOM } from "solid-element";
import { onMount, onCleanup, Show, createEffect } from "solid-js";
import { useCommander } from "./hooks";
import { CommanderInput } from "./CommanderInput";
import { CommanderEntries } from "./CommanderEntries";
import { TrackerView } from "./TrackerView";
import { TabBar } from "./TabBar";
import type { MdCommanderProps } from "./types";
import {loadElementSrc, resolvePath} from "../utils/path";
import {loadCommandTemplates} from "./utils/commandTemplates";

customElement<MdCommanderProps>(
  "md-commander",
  { placeholder: "", class: "", height: "", commandTemplates: "" },
  (props, { element }) => {
    noShadowDOM();
    const {articlePath, rawSrc} = loadElementSrc(element as any);
    const commander = useCommander(props.commands);
    createEffect(async () => {
      if(!rawSrc) return;
      await loadCommandTemplates(commander.commands, resolvePath(articlePath, rawSrc));
    });

    const handleKeyDown = (e: KeyboardEvent) => {
      if (commander.showCompletions() && commander.completions().length > 0) {
        if (e.key === "ArrowDown") {
          e.preventDefault();
          commander.setSelectedCompletion(
            (prev) => (prev + 1) % commander.completions().length,
          );
          return;
        }
        if (e.key === "ArrowUp") {
          e.preventDefault();
          commander.setSelectedCompletion(
            (prev) => (prev - 1 + commander.completions().length) % commander.completions().length,
          );
          return;
        }
        if (e.key === "Tab") {
          e.preventDefault();
          commander.acceptCompletion();
          return;
        }
        if (e.key === "Escape") {
          commander.setShowCompletions(false);
          return;
        }
      }

      // 补全未打开时，使用上下键浏览历史
      if (e.key === "ArrowUp" && !commander.showCompletions()) {
        e.preventDefault();
        commander.navigateHistory("up");
        return;
      }
      if (e.key === "ArrowDown" && !commander.showCompletions()) {
        e.preventDefault();
        commander.navigateHistory("down");
        return;
      }

      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        commander.handleCommand();
      }
    };

    const heightStyle = () => props.height || "400px";

    onMount(() => {
      const handleClickOutside = (e: MouseEvent) => {
        if (!element?.contains(e.target as Node)) {
          commander.setShowCompletions(false);
        }
      };
      document.addEventListener("click", handleClickOutside);
      onCleanup(() => document.removeEventListener("click", handleClickOutside));
    });

    return (
      <div
        class={`md-commander flex flex-col border border-gray-300 rounded-lg overflow-hidden ${props.class || ""}`}
        style={{ height: heightStyle() }}
      >
        {/* 标签页导航 */}
        <TabBar
          mode={commander.viewMode}
          onModeChange={commander.setViewMode}
        />

        {/* 内容区域：历史或追踪 */}
        <Show
          when={commander.viewMode() === "history"}
          fallback={
            <TrackerView
              items={commander.trackerItems}
              onEditAttribute={(index, attrName, attr) =>
                  commander.updateTrackerAttributeByIndex(index, attrName, attr)
              }
              onClassesChange={(index, classes) =>
                commander.updateTrackerClassesByIndex(index, classes)
              }
              onRemoveClass={commander.removeTrackerItemClassByIndex}
              onMoveUp={(index) => commander.moveTrackerItemByIndex(index, "up")}
              onMoveDown={(index) => commander.moveTrackerItemByIndex(index, "down")}
              onRemove={(index) => commander.removeTrackerItemByIndex(index)}
            />
          }
        >
          <CommanderEntries
            entries={commander.entries}
            onCommandClick={(cmd) => commander.setInputValue(cmd)}
          />
        </Show>

        {/* 命令输入框 */}
        <div class="relative border-t border-gray-300">
          <CommanderInput
            placeholder={props.placeholder}
            inputValue={commander.inputValue}
            onInput={(e) => {
              commander.setInputValue((e.target as HTMLInputElement).value);
              commander.updateCompletions();
            }}
            onKeyDown={handleKeyDown}
            onFocus={() => {
              commander.setIsFocused(true);
              commander.updateCompletions();
            }}
            onBlur={() => commander.setIsFocused(false)}
            onSubmit={commander.handleCommand}
            showCompletions={commander.showCompletions}
            completions={commander.completions}
            selectedCompletion={commander.selectedCompletion}
            onSelectCompletion={commander.setSelectedCompletion}
            onAcceptCompletion={commander.acceptCompletion}
          />
        </div>
      </div>
    );
  },
);
