import { A, useParams } from '@solidjs/router';
import { createResource, Show } from 'solid-js';
import AdminShell from '~/components/AdminShell';

const API = '/api/gateway';

type KbArticle = {
  id: string;
  title: string;
  slug?: string;
  content?: string;
  body?: string;
  status?: string;
  category?: string;
  category_id?: string;
  updated_at?: string;
  created_at?: string;
};

async function loadArticle(id: string): Promise<KbArticle | null> {
  try {
    const res = await fetch(`${API}/api/admin/kb/articles/${id}`);
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

export default function KbArticleDetailPage() {
  const params = useParams();
  const [article] = createResource(() => params.id, loadArticle);

  return (
    <AdminShell>
      <div class="page-hero-card page-actions">
        <div>
          <h1 class="page-title">KB Article Detail</h1>
          <p class="page-subtitle">Metadata and safe content preview for this article.</p>
        </div>
        <div class="page-actions-right">
          <A class="btn" href="/admin/kb/articles">Back to Articles</A>
          <A class="btn primary" href={`/admin/kb/articles/${params.id}/edit`}>Edit Article</A>
        </div>
      </div>

      <Show when={article.loading}>
        <section class="card"><p class="notice">Loading article...</p></section>
      </Show>

      <Show when={!article.loading && !article()}>
        <section class="card"><p class="notice">Article not found.</p></section>
      </Show>

      <Show when={article()}>
        <div class="detail-layout">
          <section class="card">
            <h2 style="margin-bottom:10px">Metadata</h2>
            <div class="field-grid-2">
              <div class="kv-item"><p class="kv-label">Title</p><p class="kv-value">{article()!.title || '—'}</p></div>
              <div class="kv-item"><p class="kv-label">Status</p><p class="kv-value">{article()!.status || '—'}</p></div>
              <div class="kv-item"><p class="kv-label">Slug</p><p class="kv-value">{article()!.slug || '—'}</p></div>
              <div class="kv-item"><p class="kv-label">Category</p><p class="kv-value">{article()!.category || article()!.category_id || '—'}</p></div>
              <div class="kv-item"><p class="kv-label">Created At</p><p class="kv-value">{article()!.created_at ? new Date(article()!.created_at!).toLocaleString() : '—'}</p></div>
              <div class="kv-item"><p class="kv-label">Updated At</p><p class="kv-value">{article()!.updated_at ? new Date(article()!.updated_at!).toLocaleString() : '—'}</p></div>
            </div>
          </section>

          <section class="card">
            <h2 style="margin-bottom:10px">Content</h2>
            <pre class="json" style="max-height:720px;white-space:pre-wrap">{article()!.content || article()!.body || 'No content'}</pre>
          </section>
        </div>
      </Show>
    </AdminShell>
  );
}
