'use client';

/**
 * M1-step4 Admin Memory 管理页
 *
 * 列 + 新建 + 删除 ownerScope=ORG 共享 memory。这些 memory 对 org 内所有用户每次 turn
 * 自动注入 system prompt，是"团队级共识 / 公司政策"的强约束承载。
 *
 * Endpoints：
 *   GET    /api/v1/agent/admin/memories                列本 org 全部 ORG-scope memory
 *   POST   /api/v1/agent/admin/memories                新建（ownerScope 强制 ORG）
 *   DELETE /api/v1/agent/admin/memories/:id            硬删
 *
 * 权限：Administrator / ITAdmin / agent.admin 角色任一。
 */

import { useCallback, useEffect, useState } from 'react';
import apiClient from '@/lib/api-client';
import { Loader2, Plus, RefreshCw, Trash2, Shield } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import {
  MEMORY_CATEGORIES,
  type AgentMemory,
  type MemoryCategory,
} from '@/services/api/agent-memory';

interface OrgMemoryListResponse {
  items: AgentMemory[];
}

export default function AdminMemoryPage() {
  const { t } = useTranslation();
  const [items, setItems] = useState<AgentMemory[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState<MemoryCategory | 'ALL'>('ALL');
  const [creating, setCreating] = useState(false);
  const [draftContent, setDraftContent] = useState('');
  const [draftCategory, setDraftCategory] = useState<MemoryCategory>('PROJECT');

  const refresh = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = filter === 'ALL' ? {} : { category: filter };
      const resp = (await apiClient.get('/agent/admin/memories', { params })) as unknown as OrgMemoryListResponse;
      setItems(resp.items);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, [filter]);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  const submitCreate = async () => {
    const content = draftContent.trim();
    if (!content) return;
    try {
      const created = (await apiClient.post('/agent/admin/memories', {
        content,
        category: draftCategory,
        scope: 'GLOBAL',
      })) as unknown as AgentMemory;
      setItems((prev) => [created, ...prev]);
      setDraftContent('');
      setCreating(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    }
  };

  const remove = async (id: string) => {
    if (typeof window !== 'undefined' && !window.confirm(t.agent.memory.deleteConfirm)) return;
    try {
      await apiClient.delete(`/agent/admin/memories/${id}`);
      setItems((prev) => prev.filter((m) => m.id !== id));
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    }
  };

  return (
    <div className="mx-auto max-w-5xl p-6">
      <header className="mb-6 flex items-start justify-between gap-3">
        <div>
          <h1 className="flex items-center gap-2 text-2xl font-semibold text-neutral-900 dark:text-neutral-100">
            <Shield className="h-5 w-5 text-blue-600 dark:text-blue-400" aria-hidden />
            {t.agent.admin.memory.title}
          </h1>
          <p className="mt-1 text-sm text-neutral-500 dark:text-neutral-400">
            {t.agent.admin.memory.subtitle}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setCreating(true)}
            className="flex items-center gap-1 rounded bg-neutral-900 px-3 py-1.5 text-xs text-white transition hover:bg-neutral-700 dark:bg-neutral-100 dark:text-neutral-900 dark:hover:bg-neutral-200"
          >
            <Plus className="h-3.5 w-3.5" aria-hidden />
            {t.agent.admin.memory.add}
          </button>
          <button
            type="button"
            onClick={() => void refresh()}
            className="rounded border border-stone-300 p-1.5 text-neutral-600 transition hover:bg-stone-100 dark:border-neutral-700 dark:text-neutral-400 dark:hover:bg-neutral-800"
            aria-label="refresh"
          >
            <RefreshCw className="h-3.5 w-3.5" aria-hidden />
          </button>
        </div>
      </header>

      {error ? (
        <div className="mb-3 rounded border border-red-300 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-300">
          {error}
        </div>
      ) : null}

      <div className="mb-3 flex flex-wrap items-center gap-2">
        <span className="text-xs text-neutral-500 dark:text-neutral-400">
          {t.agent.memory.categoryLabel}:
        </span>
        {(['ALL', ...MEMORY_CATEGORIES] as const).map((cat) => (
          <button
            key={cat}
            type="button"
            onClick={() => setFilter(cat)}
            aria-pressed={filter === cat}
            className={`rounded px-2 py-0.5 text-xs transition ${
              filter === cat
                ? 'bg-neutral-900 text-white dark:bg-neutral-100 dark:text-neutral-900'
                : 'border border-stone-300 text-neutral-600 hover:bg-stone-100 dark:border-neutral-700 dark:text-neutral-400 dark:hover:bg-neutral-800'
            }`}
          >
            {cat === 'ALL' ? t.agent.admin.memory.allCategories : t.agent.memory.categories[cat]}
          </button>
        ))}
      </div>

      {creating ? (
        <div className="mb-4 rounded border border-stone-300 bg-stone-50 p-3 dark:border-neutral-700 dark:bg-neutral-900">
          <textarea
            value={draftContent}
            onChange={(e) => setDraftContent(e.target.value)}
            placeholder={t.agent.admin.memory.placeholder}
            autoFocus
            rows={3}
            className="w-full resize-none rounded border border-stone-300 bg-white px-2 py-1 text-sm text-neutral-900 placeholder:text-neutral-400 focus:border-neutral-500 focus:outline-none dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-100"
          />
          <div className="mt-2 flex flex-wrap items-center gap-1">
            <span className="text-xs text-neutral-500 dark:text-neutral-400">
              {t.agent.memory.categoryLabel}:
            </span>
            {MEMORY_CATEGORIES.map((cat) => (
              <button
                key={cat}
                type="button"
                onClick={() => setDraftCategory(cat)}
                aria-pressed={draftCategory === cat}
                className={`rounded px-1.5 py-0.5 text-xs transition ${
                  draftCategory === cat
                    ? 'bg-neutral-900 text-white dark:bg-neutral-100 dark:text-neutral-900'
                    : 'border border-stone-300 text-neutral-600 hover:bg-stone-100 dark:border-neutral-700 dark:text-neutral-400 dark:hover:bg-neutral-800'
                }`}
              >
                {t.agent.memory.categories[cat]}
              </button>
            ))}
          </div>
          <div className="mt-3 flex gap-2">
            <button
              type="button"
              onClick={submitCreate}
              disabled={draftContent.trim().length === 0}
              className="rounded bg-neutral-900 px-3 py-1 text-xs text-white transition hover:bg-neutral-700 disabled:bg-neutral-300 dark:bg-neutral-100 dark:text-neutral-900 dark:disabled:bg-neutral-700 dark:disabled:text-neutral-500"
            >
              {t.agent.memory.save}
            </button>
            <button
              type="button"
              onClick={() => {
                setCreating(false);
                setDraftContent('');
              }}
              className="rounded border border-stone-300 px-3 py-1 text-xs text-neutral-700 transition hover:bg-stone-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              {t.agent.memory.cancel}
            </button>
          </div>
        </div>
      ) : null}

      {loading ? (
        <div className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400">
          <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
          loading...
        </div>
      ) : items.length === 0 ? (
        <div className="rounded border border-dashed border-stone-300 px-4 py-6 text-center text-sm text-neutral-400 dark:border-neutral-700">
          {t.agent.admin.memory.empty}
        </div>
      ) : (
        <table className="w-full border-collapse text-xs">
          <thead>
            <tr className="border-b border-stone-300 text-left text-neutral-500 dark:border-neutral-700 dark:text-neutral-400">
              <th className="py-2 pr-2 font-medium">{t.agent.memory.categoryLabel}</th>
              <th className="py-2 pr-2 font-medium">Content</th>
              <th className="py-2 pr-2 font-medium">Scope</th>
              <th className="py-2 pr-2 font-medium">Updated</th>
              <th className="py-2 font-medium" aria-label="actions" />
            </tr>
          </thead>
          <tbody>
            {items.map((m) => (
              <tr
                key={m.id}
                className="border-b border-stone-200 hover:bg-stone-50 dark:border-neutral-800 dark:hover:bg-neutral-900"
              >
                <td className="py-2 pr-2">
                  <span className="rounded bg-stone-100 px-1.5 py-0.5 text-[10px] text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300">
                    {t.agent.memory.categories[m.category]}
                  </span>
                </td>
                <td className="py-2 pr-2 text-neutral-800 dark:text-neutral-200">{m.content}</td>
                <td className="py-2 pr-2 text-neutral-500 dark:text-neutral-400">{m.scope}</td>
                <td className="py-2 pr-2 text-neutral-500 dark:text-neutral-400">
                  {new Date(m.updatedAt).toISOString().slice(0, 16).replace('T', ' ')}
                </td>
                <td className="py-2">
                  <button
                    type="button"
                    onClick={() => void remove(m.id)}
                    aria-label={t.agent.memory.delete}
                    className="rounded p-1 text-neutral-400 transition hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950"
                  >
                    <Trash2 className="h-3.5 w-3.5" aria-hidden />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}
