import { useMemo, useState } from 'react'
import {
  deleteCommand,
  deleteCommandCategory,
  saveCommand,
  saveCommandCategory
} from '../ipc'
import type { CommandItem, Config } from '../types'
import { CategoryManager } from './CategoryManager'
import { ConfirmDialog, Modal } from './Modal'
import { IconEdit, IconPlus, IconStar, IconTrash } from './Icons'

interface Props {
  config: Config
  onConfigChange: (c: Config) => void
}

function emptyCommand(): CommandItem {
  return {
    id: crypto.randomUUID(),
    name: '',
    content: '',
    categoryId: null,
    projects: null,
    starred: false,
    updatedAt: 0
  }
}

export function CommandsPage({ config, onConfigChange }: Props) {
  const [filter, setFilter] = useState('')
  const [categoryFilter, setCategoryFilter] = useState('')
  const [editing, setEditing] = useState<CommandItem | null>(null)
  const [deleting, setDeleting] = useState<CommandItem | null>(null)
  const [managingCategories, setManagingCategories] = useState(false)

  const catName = (id: string | null) =>
    config.commandCategories.find((c) => c.id === id)?.name ?? '未分类'

  const shown = useMemo(
    () =>
      config.commands
        .filter((c) => {
          if (categoryFilter && (c.categoryId ?? '') !== categoryFilter) return false
          if (filter) {
            const f = filter.toLowerCase()
            return c.name.toLowerCase().includes(f) || c.content.toLowerCase().includes(f)
          }
          return true
        })
        // 加星的靠前（稳定排序保持组内原顺序）
        .sort((a, b) => Number(b.starred) - Number(a.starred)),
    [config.commands, filter, categoryFilter]
  )

  const toggleStar = async (cmd: typeof config.commands[number]) => {
    onConfigChange(await saveCommand({ ...cmd, starred: !cmd.starred }))
  }

  return (
    <div className="page">
      <h2>指令库</h2>
      <p className="page-desc">
        常用提示词与指令。每条指令可设置分类和项目可见范围，在终端右侧的指令面板中一键填入或发送。
      </p>
      <div className="toolbar">
        <button className="btn primary" onClick={() => setEditing(emptyCommand())}>
          <IconPlus />
          新建指令
        </button>
        <select
          className="select"
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
        >
          <option value="">全部分类</option>
          {config.commandCategories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
        <input
          className="input"
          style={{ width: 220 }}
          placeholder="搜索名称或内容"
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
        />
        <div className="spacer" />
        <button className="btn" onClick={() => setManagingCategories(true)}>
          管理分类
        </button>
      </div>
      <div className="row-list">
        {shown.length === 0 && <div className="empty-hint">没有指令</div>}
        {shown.map((cmd) => (
          <div key={cmd.id} className="row">
            <div className="row-main">
              <div className="row-title">
                {cmd.name}{' '}
                <span className="badge" style={{ marginLeft: 6 }}>
                  {catName(cmd.categoryId)}
                </span>{' '}
                <span className={`badge ${cmd.projects ? '' : 'accent'}`}>
                  {cmd.projects ? `${cmd.projects.length} 个项目` : '所有项目'}
                </span>
              </div>
              <div className="row-sub">{cmd.content}</div>
            </div>
            <div className="row-actions">
              <button
                className={`btn small star-btn ${cmd.starred ? 'on' : ''}`}
                title={cmd.starred ? '取消加星' : '加星（靠前显示）'}
                onClick={() => void toggleStar(cmd)}
              >
                <IconStar fill={cmd.starred ? 'currentColor' : 'none'} />
              </button>
              <button className="btn small" title="编辑" onClick={() => setEditing({ ...cmd })}>
                <IconEdit />
              </button>
              <button className="btn small danger" title="删除" onClick={() => setDeleting(cmd)}>
                <IconTrash />
              </button>
            </div>
          </div>
        ))}
      </div>

      {editing && (
        <CommandEditDialog
          command={editing}
          config={config}
          onClose={() => setEditing(null)}
          onSave={async (item) => {
            onConfigChange(await saveCommand(item))
            setEditing(null)
          }}
        />
      )}

      {deleting && (
        <ConfirmDialog
          title="删除指令"
          message={`确定删除指令「${deleting.name}」？`}
          confirmText="删除"
          danger
          onCancel={() => setDeleting(null)}
          onConfirm={async () => {
            onConfigChange(await deleteCommand(deleting.id))
            setDeleting(null)
          }}
        />
      )}

      {managingCategories && (
        <CategoryManager
          title="管理指令分类"
          categories={config.commandCategories}
          onSave={saveCommandCategory}
          onDelete={deleteCommandCategory}
          onConfigChange={onConfigChange}
          onClose={() => setManagingCategories(false)}
        />
      )}
    </div>
  )
}

interface EditProps {
  command: CommandItem
  config: Config
  onSave: (item: CommandItem) => Promise<void>
  onClose: () => void
}

function CommandEditDialog({ command, config, onSave, onClose }: EditProps) {
  const [name, setName] = useState(command.name)
  const [content, setContent] = useState(command.content)
  const [categoryId, setCategoryId] = useState(command.categoryId ?? '')
  const [scopeAll, setScopeAll] = useState(command.projects === null)
  const [selected, setSelected] = useState<Set<string>>(new Set(command.projects ?? []))
  const isNew = !config.commands.some((c) => c.id === command.id)

  const toggleProject = (path: string) => {
    setSelected((prev) => {
      const next = new Set(prev)
      if (next.has(path)) next.delete(path)
      else next.add(path)
      return next
    })
  }

  const valid = name.trim() && content.trim() && (scopeAll || selected.size > 0)

  return (
    <Modal
      title={isNew ? '新建指令' : '编辑指令'}
      width={560}
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose}>
            取消
          </button>
          <button
            className="btn primary"
            disabled={!valid}
            onClick={() =>
              void onSave({
                ...command,
                name: name.trim(),
                content,
                categoryId: categoryId || null,
                projects: scopeAll ? null : [...selected]
              })
            }
          >
            保存
          </button>
        </>
      }
    >
      <label className="label">名称</label>
      <input
        className="input"
        style={{ width: '100%' }}
        value={name}
        autoFocus
        onChange={(e) => setName(e.target.value)}
      />

      <label className="label">内容（支持多行，填入终端时按一次粘贴处理）</label>
      <textarea
        className="input"
        style={{ width: '100%', minHeight: 120 }}
        value={content}
        onChange={(e) => setContent(e.target.value)}
      />

      <label className="label">分类</label>
      <select
        className="select"
        style={{ width: '100%' }}
        value={categoryId}
        onChange={(e) => setCategoryId(e.target.value)}
      >
        <option value="">未分类</option>
        {config.commandCategories.map((c) => (
          <option key={c.id} value={c.id}>
            {c.name}
          </option>
        ))}
      </select>

      <label className="label">项目可见范围</label>
      <div style={{ display: 'flex', gap: 16, marginBottom: 6 }}>
        <label className="check-item" style={{ padding: 0 }}>
          <input type="radio" checked={scopeAll} onChange={() => setScopeAll(true)} />
          所有项目
        </label>
        <label className="check-item" style={{ padding: 0 }}>
          <input type="radio" checked={!scopeAll} onChange={() => setScopeAll(false)} />
          指定项目
        </label>
      </div>
      {!scopeAll && (
        <div className="check-list">
          {config.projects.map((p) => (
            <label key={p.path} className="check-item">
              <input
                type="checkbox"
                checked={selected.has(p.path)}
                onChange={() => toggleProject(p.path)}
              />
              <span title={p.path}>{p.name}</span>
            </label>
          ))}
          {/* 已被移除的项目仍保留引用，便于将来恢复 */}
          {[...selected]
            .filter((path) => !config.projects.some((p) => p.path === path))
            .map((path) => (
              <label key={path} className="check-item" style={{ color: 'var(--text-faint)' }}>
                <input type="checkbox" checked onChange={() => toggleProject(path)} />
                <span title={path}>{path}（已移除的项目）</span>
              </label>
            ))}
          {config.projects.length === 0 && selected.size === 0 && (
            <div style={{ padding: 8, color: 'var(--text-faint)' }}>还没有项目</div>
          )}
        </div>
      )}
    </Modal>
  )
}
