'use client';
/**
 * BannedWordsTab — 违禁词库管理（三级可调）
 */
import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { BannedWord, CreateBannedWordRequest, BannedWordLevel } from '@/types/index';
import { PaginatedResponse } from '@/types/index';
import { BannedWordsTable } from './BannedWordsTable';

export function BannedWordsTab() {
  const [words, setWords] = useState<BannedWord[]>([]);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState<CreateBannedWordRequest>({
    word: '', level: 'soft_warn', replacement: null, updatable: true,
  });
  const [saving, setSaving] = useState(false);

  useEffect(() => { loadWords(); }, []);

  async function loadWords() {
    setLoading(true);
    try {
      const data = await api.get<PaginatedResponse<BannedWord>>('/api/v1/banned-words');
      setWords(data.items);
    } finally { setLoading(false); }
  }

  async function handleAdd(e: React.FormEvent) {
    e.preventDefault();
    if (!form.word.trim()) return;
    setSaving(true);
    try {
      await api.post('/api/v1/banned-words', form);
      setForm({ word: '', level: 'soft_warn', replacement: null, updatable: true });
      await loadWords();
    } finally { setSaving(false); }
  }

  async function handleDelete(id: number) {
    if (!confirm('确认删除此违禁词？')) return;
    await api.delete(`/api/v1/banned-words/${id}`);
    setWords((ws) => ws.filter((w) => w.id !== id));
  }

  return (
    <div className="space-y-6">
      <p className="text-sm text-text-secondary">
        三级：自动改写（替换）/ 软提示（生成后提醒）/ 硬拦截（生成前阻止）
      </p>
      <form onSubmit={handleAdd} className="flex gap-3 items-end flex-wrap">
        <div>
          <label htmlFor="bw-word" className="block text-sm font-medium mb-1">违禁词</label>
          <input id="bw-word" value={form.word}
            onChange={(e) => setForm((f) => ({ ...f, word: e.target.value }))}
            className="border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange w-32"
            aria-required="true"
          />
        </div>
        <div>
          <label htmlFor="bw-level" className="block text-sm font-medium mb-1">级别</label>
          <select id="bw-level" value={form.level}
            onChange={(e) => setForm((f) => ({ ...f, level: e.target.value as BannedWordLevel }))}
            className="border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange">
            <option value="auto_fix">自动改写</option>
            <option value="soft_warn">软提示</option>
            <option value="hard_block">硬拦截</option>
          </select>
        </div>
        <div>
          <label htmlFor="bw-replace" className="block text-sm font-medium mb-1">替换词（可选）</label>
          <input id="bw-replace" value={form.replacement ?? ''}
            onChange={(e) => setForm((f) => ({ ...f, replacement: e.target.value || null }))}
            placeholder="如：提亮"
            className="border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange w-28"
          />
        </div>
        <button type="submit" disabled={saving} aria-label="添加违禁词"
          className="bg-brand-orange text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-orange-600 disabled:opacity-50">
          {saving ? '添加中…' : '添加'}
        </button>
      </form>
      {loading ? (
        <div className="text-text-secondary text-sm" aria-busy="true">加载中…</div>
      ) : (
        <BannedWordsTable words={words} onDelete={handleDelete} />
      )}
    </div>
  );
}
