import { useMemo, useState } from 'react'
import { deleteRule, deleteRuleCategory, saveRule, saveRuleCategory } from '../ipc'
import type { Config, RuleItem } from '../types'
import { CategoryManager } from './CategoryManager'
import { ConfirmDialog, Modal } from './Modal'
import { IconEdit, IconPlus, IconTrash } from './Icons'

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

function emptyRule(): RuleItem {
  return { id: crypto.randomUUID(), name: '', content: '', categoryId: null, updatedAt: 0 }
}

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

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

  const shown = useMemo(
    () =>
      config.rules.filter((r) => {
        if (categoryFilter && (r.categoryId ?? '') !== categoryFilter) return false
        if (filter) {
          const f = filter.toLowerCase()
          return r.name.toLowerCase().includes(f) || r.content.toLowerCase().includes(f)
        }
        return true
      }),
    [config.rules, filter, categoryFilter]
  )

  return (
    <div className="page">
      <h2>规则库</h2>
      <p className="page-desc">
        可复用的项目规则片段。在项目的「项目规则」页中注入：规则内容写入项目的 .claude/rules/
        目录，并在 CLAUDE.md 中添加 @ 引用行。注入后对新开的会话生效。
      </p>
      <div className="toolbar">
        <button className="btn primary" onClick={() => setEditing(emptyRule())}>
          <IconPlus />
          新建规则
        </button>
        <select
          className="select"
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
        >
          <option value="">全部分类</option>
          {config.ruleCategories.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((rule) => (
          <div key={rule.id} className="row">
            <div className="row-main">
              <div className="row-title">
                {rule.name}{' '}
                <span className="badge" style={{ marginLeft: 6 }}>
                  {catName(rule.categoryId)}
                </span>
              </div>
              <div className="row-sub">{rule.content}</div>
            </div>
            <div className="row-actions">
              <button className="btn small" title="编辑" onClick={() => setEditing({ ...rule })}>
                <IconEdit />
              </button>
              <button className="btn small danger" title="删除" onClick={() => setDeleting(rule)}>
                <IconTrash />
              </button>
            </div>
          </div>
        ))}
      </div>

      {editing && (
        <RuleEditDialog
          rule={editing}
          config={config}
          onClose={() => setEditing(null)}
          onSave={async (item) => {
            onConfigChange(await saveRule(item))
            setEditing(null)
          }}
        />
      )}

      {deleting && (
        <ConfirmDialog
          title="删除规则"
          message={`确定删除规则「${deleting.name}」？\n已注入到项目中的副本不会被删除。`}
          confirmText="删除"
          danger
          onCancel={() => setDeleting(null)}
          onConfirm={async () => {
            onConfigChange(await deleteRule(deleting.id))
            setDeleting(null)
          }}
        />
      )}

      {managingCategories && (
        <CategoryManager
          title="管理规则分类"
          categories={config.ruleCategories}
          onSave={saveRuleCategory}
          onDelete={deleteRuleCategory}
          onConfigChange={onConfigChange}
          onClose={() => setManagingCategories(false)}
        />
      )}
    </div>
  )
}

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

function RuleEditDialog({ rule, config, onSave, onClose }: EditProps) {
  const [name, setName] = useState(rule.name)
  const [content, setContent] = useState(rule.content)
  const [categoryId, setCategoryId] = useState(rule.categoryId ?? '')
  const isNew = !config.rules.some((r) => r.id === rule.id)

  return (
    <Modal
      title={isNew ? '新建规则' : '编辑规则'}
      width={560}
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose}>
            取消
          </button>
          <button
            className="btn primary"
            disabled={!name.trim() || !content.trim()}
            onClick={() =>
              void onSave({
                ...rule,
                name: name.trim(),
                content,
                categoryId: categoryId || null
              })
            }
          >
            保存
          </button>
        </>
      }
    >
      <label className="label">名称（注入时作为规则文件名）</label>
      <input
        className="input"
        style={{ width: '100%' }}
        value={name}
        autoFocus
        onChange={(e) => setName(e.target.value)}
      />

      <label className="label">规则内容（Markdown）</label>
      <textarea
        className="input"
        style={{ width: '100%', minHeight: 180 }}
        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.ruleCategories.map((c) => (
          <option key={c.id} value={c.id}>
            {c.name}
          </option>
        ))}
      </select>
    </Modal>
  )
}
