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

const API = '';

function getToken(): string {
  return typeof sessionStorage !== 'undefined'
    ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
    : '';
}

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 token = getToken();
    const res = await fetch(`${API}/api/admin/kb/articles/${id}`, {
      headers: {
        Accept: 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
      },
      credentials: 'include',
    });
    if (!res.ok) return null;
    const data = await res.json();
    return {
      ...data,
      content: data?.content ?? data?.body ?? '',
      body: data?.body ?? data?.content ?? '',
    };
  } catch {
    return null;
  }
}

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

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
      <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
        <div>
          <h1 class="text-xl font-semibold text-gray-900">KB Article Detail</h1>
          <p class="text-sm text-gray-500 mt-0.5">Metadata and safe content preview for this article.</p>
        </div>
        <div class="flex items-center gap-2">
          <A class="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href="/admin/kb/articles">Back to Articles</A>
          <A class="btn-primary" href={`/admin/kb/articles/${params.id}/edit`}>Edit Article</A>
        </div>
      </div>
      <div class="p-6 flex-1">

      <Show when={article.loading}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Loading article...</p></section>
      </Show>

      <Show when={!article.loading && !article()}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Article not found.</p></section>
      </Show>

      <Show when={article()}>
        <div class="detail-layout">
          <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
            <h2 style="margin-bottom:10px">Metadata</h2>
            <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-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="rounded-xl border border-gray-200 bg-white shadow-sm">
            <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>
      </div>
      </div>
  );
}
