import { useState } from "react";
import clsx from "clsx";
import { Plus, Pencil, Trash2, Zap, ArrowLeft } from "lucide-react";
import { useAppStore } from "../../store/useAppStore";
import type { Shortcut, ShortcutType } from "../../store/types";
import { runShortcut } from "../../api/tauri";
import { getIcon, ICON_OPTIONS } from "./iconMap";
import styles from "./ShortcutsPanel.module.css";

/**
 * 主工具栏上的横向快捷按钮区
 */
export function ShortcutsBar({ disabled = false }: { disabled?: boolean }) {
  const shortcuts = useAppStore((s) => s.shortcuts);
  const setActivePanel = useAppStore((s) => s.setActivePanel);

  async function exec(s: Shortcut) {
    try {
      await runShortcut(s);
    } catch (e) {
      console.error("[DeskFloat] run shortcut failed", e);
      alert(`执行失败：${(e as Error).message || e}`);
    }
  }

  if (shortcuts.length === 0) {
    return (
      <button
        className={styles.emptyBtn}
        title="添加你的第一个快捷方式"
        onClick={() => setActivePanel("shortcuts")}
        disabled={disabled}
      >
        <Plus size={12} /> 添加快捷方式
      </button>
    );
  }

  return (
    <>
      {shortcuts.map((s) => {
        const Icon = getIcon(s.icon);
        return (
          <button
            key={s.id}
            className={styles.barBtn}
            title={`${s.label}\n${s.type.toUpperCase()}: ${s.target}`}
            onClick={() => exec(s)}
            onContextMenu={(e) => {
              e.preventDefault();
              setActivePanel("shortcuts");
            }}
            disabled={disabled}
          >
            <Icon size={14} />
            <span>{s.label}</span>
          </button>
        );
      })}
      <button
        className={styles.barAddBtn}
        title="管理 / 新增快捷方式"
        onClick={() => setActivePanel("shortcuts")}
        disabled={disabled}
      >
        <Plus size={12} />
      </button>
    </>
  );
}

/**
 * 展开的"管理快捷方式"面板：列表视图 / 编辑视图（inline 切换）
 */
export function ShortcutsPanel() {
  const shortcuts = useAppStore((s) => s.shortcuts);
  const removeShortcut = useAppStore((s) => s.removeShortcut);

  // null = 列表视图；"new" = 新增；Shortcut = 编辑现有
  const [editing, setEditing] = useState<Shortcut | "new" | null>(null);

  if (editing) {
    return (
      <ShortcutEditor
        initial={editing === "new" ? null : editing}
        onClose={() => setEditing(null)}
      />
    );
  }

  return (
    <div className={styles.panel}>
      <div className={styles.header}>
        <div className={styles.title}>
          <Zap size={14} /> 快捷方式
          <span className={styles.muted}>{shortcuts.length}</span>
        </div>
        <button className={styles.addBtn} onClick={() => setEditing("new")}>
          <Plus size={12} /> 新增
        </button>
      </div>

      <div className={styles.list}>
        {shortcuts.length === 0 && (
          <div className={styles.empty}>暂无快捷方式，点击右上角 “+ 新增”</div>
        )}
        {shortcuts.map((s) => {
          const Icon = getIcon(s.icon);
          return (
            <div key={s.id} className={styles.row}>
              <div className={styles.rowIcon}>
                <Icon size={14} />
              </div>
              <div className={styles.rowMain}>
                <div className={styles.rowLabel}>{s.label}</div>
                <div className={styles.rowMeta}>
                  <span className={styles.typeTag}>{s.type}</span>
                  <span className={styles.target}>{s.target}</span>
                </div>
              </div>
              <div className={styles.rowActions}>
                <button
                  className={styles.iconBtn}
                  title="编辑"
                  onClick={() => setEditing(s)}
                >
                  <Pencil size={12} />
                </button>
                <button
                  className={clsx(styles.iconBtn, styles.danger)}
                  title="删除"
                  onClick={() => removeShortcut(s.id)}
                >
                  <Trash2 size={12} />
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ShortcutEditor({
  initial,
  onClose,
}: {
  initial: Shortcut | null;
  onClose: () => void;
}) {
  const addShortcut = useAppStore((s) => s.addShortcut);
  const updateShortcut = useAppStore((s) => s.updateShortcut);

  const [label, setLabel] = useState(initial?.label ?? "");
  const [icon, setIcon] = useState(initial?.icon ?? "zap");
  const [type, setType] = useState<ShortcutType>(initial?.type ?? "url");
  const [target, setTarget] = useState(initial?.target ?? "");
  const [argsText, setArgsText] = useState((initial?.args ?? []).join(" "));
  const [cwd, setCwd] = useState(initial?.cwd ?? "");
  const [silent, setSilent] = useState(initial?.silent ?? false);

  function save() {
    if (!label.trim() || !target.trim()) {
      alert("名称和目标都不能为空");
      return;
    }
    const args =
      argsText
        .trim()
        .split(/\s+/)
        .filter(Boolean) ?? [];
    const data = {
      label: label.trim(),
      icon,
      type,
      target: target.trim(),
      args,
      cwd: cwd.trim() || undefined,
      silent: type === "cmd" || type === "powershell" ? silent : undefined,
    };
    if (initial) updateShortcut(initial.id, data);
    else addShortcut(data);
    onClose();
  }

  const placeholderByType: Record<ShortcutType, string> = {
    url: "https://example.com",
    app: "C:\\Path\\To\\App.exe",
    cmd: "echo hello && pause",
    powershell: "Get-Process | Select-Object -First 5",
  };

  return (
    <div className={styles.editor}>
      <div className={styles.editorHeader}>
        <button
          className={styles.backBtn}
          onClick={onClose}
          title="返回列表"
        >
          <ArrowLeft size={14} />
        </button>
        <div className={styles.editorTitle}>
          {initial ? "编辑快捷方式" : "新增快捷方式"}
        </div>
      </div>

      <div className={styles.editorBody}>
        <div className={styles.grid2}>
          <div className={styles.field}>
            <label>名称</label>
            <input
              autoFocus
              value={label}
              onChange={(e) => setLabel(e.target.value)}
              placeholder="按钮显示文本"
            />
          </div>

          <div className={styles.field}>
            <label>类型</label>
            <div className={styles.typeRow}>
              {(["url", "app", "cmd", "powershell"] as ShortcutType[]).map(
                (t) => (
                  <button
                    key={t}
                    className={clsx(
                      styles.typeBtn,
                      type === t && styles.typeBtnActive
                    )}
                    onClick={() => setType(t)}
                  >
                    {t}
                  </button>
                )
              )}
            </div>
          </div>
        </div>

        <div className={styles.field}>
          <label>目标</label>
          <input
            value={target}
            onChange={(e) => setTarget(e.target.value)}
            placeholder={placeholderByType[type]}
          />
        </div>

        {(type === "app" || type === "cmd" || type === "powershell") && (
          <>
            <div className={styles.grid2}>
              {type === "app" ? (
                <div className={styles.field}>
                  <label>参数（空格分隔，可选）</label>
                  <input
                    value={argsText}
                    onChange={(e) => setArgsText(e.target.value)}
                    placeholder="--flag value"
                  />
                </div>
              ) : (
                <div className={styles.field} />
              )}
              <div className={styles.field}>
                <label>工作目录（可选）</label>
                <input
                  value={cwd}
                  onChange={(e) => setCwd(e.target.value)}
                  placeholder="D:\\projects\\app"
                />
              </div>
            </div>

            {(type === "cmd" || type === "powershell") && (
              <label className={styles.silentRow}>
                <input
                  type="checkbox"
                  checked={silent}
                  onChange={(e) => setSilent(e.target.checked)}
                />
                <span>静默执行（隐藏控制台窗口）</span>
                <span className={styles.silentHint}>
                  默认会弹出控制台便于查看输出；勾选后则后台静默运行
                </span>
              </label>
            )}
          </>
        )}

        <div className={styles.field}>
          <label>图标</label>
          <div className={styles.iconGrid}>
            {ICON_OPTIONS.map((o) => {
              const Icon = o.Icon;
              return (
                <button
                  key={o.name}
                  className={clsx(
                    styles.iconCell,
                    icon === o.name && styles.iconCellActive
                  )}
                  title={o.name}
                  onClick={() => setIcon(o.name)}
                >
                  <Icon size={14} />
                </button>
              );
            })}
          </div>
        </div>
      </div>

      <div className={styles.editorActions}>
        <button className={styles.cancelBtn} onClick={onClose}>
          取消
        </button>
        <button className={styles.saveBtn} onClick={save}>
          保存
        </button>
      </div>
    </div>
  );
}
