import { useEffect, useMemo, useState } from "preact/hooks";
import type { WorkbenchItem } from "../types";
import { DynamicCardBody } from "./CardBodyRenderer";

interface WorkbenchOverlayProps {
  items: WorkbenchItem[];
  onDismiss(id: string): Promise<void>;
  onPromote(id: string): Promise<void>;
}

function DismissIcon() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <path
        d="M14.5 5.5L5.5 14.5M5.5 5.5L14.5 14.5"
        fill="none"
        stroke="currentColor"
        stroke-linecap="round"
        stroke-width="1.8"
      />
    </svg>
  );
}

function PromoteIcon() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <path d="M10 4l4 4h-2.4v5H8.4V8H6l4-4Z" fill="currentColor" />
      <path
        d="M5.5 15.5h9"
        fill="none"
        stroke="currentColor"
        stroke-linecap="round"
        stroke-width="1.8"
      />
    </svg>
  );
}

function workbenchTabLabel(item: WorkbenchItem): string {
  const title = item.title.trim();
  if (!title) return "Workbench";
  return title.length > 22 ? `${title.slice(0, 22).trimEnd()}...` : title;
}

function WorkbenchQuestionBody({ item }: { item: WorkbenchItem }) {
  return (
    <div class="workbench-overlay-question">
      {item.content.trim() ? (
        <div class="workbench-overlay-question-copy">{item.content.trim()}</div>
      ) : null}
      {item.question?.trim() ? (
        <div class="workbench-overlay-question-prompt">{item.question.trim()}</div>
      ) : null}
      {item.choices?.length ? (
        <div class="workbench-overlay-question-choices">
          {item.choices.map((choice) => (
            <span key={choice} class="workbench-overlay-question-choice">
              {choice}
            </span>
          ))}
        </div>
      ) : null}
    </div>
  );
}

// biome-ignore lint/complexity/noExcessiveLinesPerFunction: this overlay owns item selection and async promote/dismiss controls together
export function WorkbenchOverlay({ items, onDismiss, onPromote }: WorkbenchOverlayProps) {
  const [activeId, setActiveId] = useState<string | null>(items[0]?.id ?? null);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [errorText, setErrorText] = useState("");

  useEffect(() => {
    if (!items.length) {
      setActiveId(null);
      return;
    }
    if (activeId && items.some((item) => item.id === activeId)) return;
    setActiveId(items[0].id);
  }, [activeId, items]);

  const activeItem = useMemo(
    () =>
      activeId
        ? (items.find((item) => item.id === activeId) ?? items[0] ?? null)
        : (items[0] ?? null),
    [activeId, items],
  );

  if (!activeItem) return null;

  const busy = busyId === activeItem.id;

  const handleDismiss = async () => {
    if (!activeItem || busy) return;
    setBusyId(activeItem.id);
    setErrorText("");
    try {
      await onDismiss(activeItem.id);
    } catch (error) {
      setErrorText(error instanceof Error ? error.message : String(error));
    } finally {
      setBusyId(null);
    }
  };

  const handlePromote = async () => {
    if (!activeItem || busy || !activeItem.promotable) return;
    setBusyId(activeItem.id);
    setErrorText("");
    try {
      await onPromote(activeItem.id);
    } catch (error) {
      setErrorText(error instanceof Error ? error.message : String(error));
    } finally {
      setBusyId(null);
    }
  };

  return (
    <div id="workbench-overlay-root" data-no-swipe="1">
      <section id="workbench-overlay" aria-label="Workbench">
        <div id="workbench-overlay-head">
          <div id="workbench-overlay-eyebrow">Workbench</div>
          <div id="workbench-overlay-actions">
            {activeItem.promotable ? (
              <button
                class="workbench-overlay-icon-btn"
                type="button"
                aria-label="Add this workbench item to the feed"
                title="Add to feed"
                disabled={busy}
                onClick={handlePromote}
              >
                <PromoteIcon />
              </button>
            ) : null}
            <button
              class="workbench-overlay-icon-btn"
              type="button"
              aria-label="Dismiss this workbench item"
              title="Dismiss"
              disabled={busy}
              onClick={handleDismiss}
            >
              <DismissIcon />
            </button>
          </div>
        </div>
        {items.length > 1 ? (
          <div id="workbench-overlay-tabs">
            {items.map((item) => (
              <button
                key={item.id}
                class={`workbench-overlay-tab${item.id === activeItem.id ? " active" : ""}`}
                type="button"
                disabled={busyId !== null && busyId !== item.id}
                onClick={() => {
                  setActiveId(item.id);
                  setErrorText("");
                }}
              >
                {workbenchTabLabel(item)}
              </button>
            ))}
          </div>
        ) : null}
        <div id="workbench-overlay-title">{activeItem.title || "Untitled workbench"}</div>
        {activeItem.contextSummary?.trim() ? (
          <div id="workbench-overlay-blurb">{activeItem.contextSummary.trim()}</div>
        ) : null}
        <div id="workbench-overlay-body">
          {activeItem.kind === "question" ? (
            <WorkbenchQuestionBody item={activeItem} />
          ) : (
            <DynamicCardBody item={activeItem} surface="workbench" />
          )}
        </div>
        <div id="workbench-overlay-footer">
          {busy ? (
            <div class="workbench-overlay-status">Saving to workbench...</div>
          ) : errorText ? (
            <div class="workbench-overlay-status error">{errorText}</div>
          ) : activeItem.promotable ? (
            <div class="workbench-overlay-status">Add to feed when it is worth keeping.</div>
          ) : (
            <div class="workbench-overlay-status">Temporary session artifact.</div>
          )}
        </div>
      </section>
    </div>
  );
}
