"use client";

import { useState, useCallback } from "react";

function copyText(text: string): Promise<void> {
  if (navigator.clipboard?.writeText) {
    return navigator.clipboard.writeText(text);
  }
  return new Promise((resolve, reject) => {
    try {
      const ta = document.createElement("textarea");
      ta.value = text;
      ta.style.position = "fixed";
      ta.style.left = "-9999px";
      document.body.appendChild(ta);
      ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
      resolve();
    } catch (e) {
      reject(e);
    }
  });
}

/** Build skills.sh / Skills CLI install command (matches server install route). */
export function skillInstallCommand(
  pkg: string,
  scope: "global" | "project",
): string {
  const parts = ["npx", "skills", "add", pkg, "-y", "--agent", "pi"];
  if (scope === "global") parts.push("-g");
  return parts.join(" ");
}

/** Build pi plugin install command (matches server packages/install route). */
export function pluginInstallCommand(
  pkgName: string,
  scope: "global" | "project",
): string {
  const source =
    pkgName.startsWith("npm:") ||
    pkgName.startsWith("git:") ||
    pkgName.startsWith("https://") ||
    pkgName.startsWith("ssh://") ||
    pkgName.startsWith("/") ||
    pkgName.startsWith(".")
      ? pkgName
      : `npm:${pkgName}`;
  return scope === "project" ? `pi install ${source} -l` : `pi install ${source}`;
}

export function InstallCommandBlock({
  command,
  note,
  label = "终端安装命令",
}: {
  command: string;
  note?: string;
  label?: string;
}) {
  const [copied, setCopied] = useState(false);

  const onCopy = useCallback(() => {
    void copyText(command).then(() => {
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1600);
    });
  }, [command]);

  return (
    <div
      style={{
        border: "1px solid var(--border)",
        borderRadius: 10,
        overflow: "hidden",
        background: "color-mix(in srgb, var(--text) 3%, var(--bg-panel))",
        minWidth: 0,
        width: "100%",
      }}
    >
      {/* Header: label + copy */}
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 8,
          padding: "8px 10px 8px 12px",
          borderBottom: "1px solid var(--border)",
          background: "color-mix(in srgb, var(--text) 2%, var(--bg-panel))",
        }}
      >
        <span
          style={{
            fontSize: 11,
            fontWeight: 600,
            color: "var(--text-dim)",
            letterSpacing: "0.02em",
            flex: "1 1 auto",
            minWidth: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {label}
        </span>
        <button
          type="button"
          onClick={onCopy}
          title={copied ? "已复制" : "复制命令"}
          aria-label={copied ? "已复制" : "复制命令"}
          style={{
            display: "inline-flex",
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            gap: 5,
            flex: "0 0 auto",
            height: 28,
            padding: "0 10px",
            borderRadius: 6,
            border: copied
              ? "1px solid var(--success-border)"
              : "1px solid var(--border)",
            background: copied ? "var(--success-soft)" : "var(--bg)",
            color: copied ? "var(--success)" : "var(--text-muted)",
            fontSize: 11,
            fontWeight: 500,
            fontFamily: "var(--font-sans)",
            cursor: "pointer",
            lineHeight: 1,
            whiteSpace: "nowrap",
          }}
        >
          {copied ? <CheckIcon /> : <CopyIcon />}
          <span>{copied ? "已复制" : "复制"}</span>
        </button>
      </div>

      {/* Command body */}
      <div
        style={{
          display: "block",
          padding: "12px 14px",
          minWidth: 0,
        }}
      >
        <div
          title={command}
          style={{
            fontFamily: "var(--font-mono)",
            fontSize: 12,
            lineHeight: 1.6,
            color: "var(--text)",
            whiteSpace: "pre-wrap",
            overflowWrap: "anywhere",
            wordBreak: "break-word",
            userSelect: "all",
            margin: 0,
          }}
        >
          <span
            style={{
              color: "var(--accent)",
              fontWeight: 600,
              userSelect: "none",
              marginRight: 6,
            }}
            aria-hidden
          >
            $
          </span>
          {command}
        </div>
      </div>

      {note ? (
        <div
          style={{
            padding: "8px 12px 10px",
            borderTop: "1px solid var(--border)",
            fontSize: 11,
            color: "var(--text-dim)",
            lineHeight: 1.45,
          }}
        >
          {note}
        </div>
      ) : null}
    </div>
  );
}

function CopyIcon() {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      style={{ display: "block", flexShrink: 0 }}
    >
      <rect x="9" y="9" width="13" height="13" rx="2" />
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      style={{ display: "block", flexShrink: 0 }}
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  );
}
