import { type Component, For, Show } from "solid-js";
import type { CommanderEntry } from "./types";
import { getResultClass } from "./hooks";

export interface CommanderEntriesProps {
  entries: () => CommanderEntry[];
  onCommandClick?: (command: string) => void;
  loading?: boolean;
  error?: string;
}

export const CommanderEntries: Component<CommanderEntriesProps> = (props) => {
  let containerRef: HTMLDivElement | undefined;

  const handleCommandClick = (command: string) => {
    if (props.onCommandClick) {
      props.onCommandClick(command);
    }
  };

  return (
    <div
      ref={containerRef}
      class="commander-entries flex-1 overflow-auto p-3 bg-white space-y-2"
    >
      <Show
        when={props.loading}
        fallback={
          <Show
            when={props.error}
            fallback={
              <Show
                when={props.entries().length > 0}
                fallback={
                  <div class="text-gray-400 text-center py-8">暂无命令执行记录</div>
                }
              >
                <For each={props.entries()}>
                  {(entry) => (
                    <div class="border-l-2 border-gray-300 pl-3 py-1">
                      <div class="flex items-center justify-between text-xs text-gray-500 mb-1">
                        <span
                          class="font-mono cursor-pointer hover:text-blue-600 hover:underline truncate max-w-64"
                          onClick={() => handleCommandClick(entry.command)}
                          title="点击复制到输入框"
                        >
                          {entry.command}
                        </span>
                        <span>
                          {entry.timestamp.toLocaleTimeString()}
                        </span>
                      </div>
                      <div
                        class={`text-sm whitespace-pre-wrap ${getResultClass(entry.result.type)}`}
                        innerHTML={entry.result.isHtml ? entry.result.message : undefined}
                      >
                        {!entry.result.isHtml && entry.result.message}
                      </div>
                    </div>
                  )}
                </For>
              </Show>
            }
          >
            <div class="text-red-500 text-center py-8">{props.error}</div>
          </Show>
        }
      >
        <div class="flex items-center justify-center h-full">
          <div class="text-gray-500 flex items-center gap-2">
            <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
            <span>加载命令模板中...</span>
          </div>
        </div>
      </Show>
    </div>
  );
};
