import { A, useNavigate, useParams } from '@solidjs/router';
import { createEffect, createResource, createSignal, 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_id?: 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 KbArticleEditPage() {
  const navigate = useNavigate();
  const params = useParams();
  const [article] = createResource(() => params.id, loadArticle);
  const [title, setTitle] = createSignal('');
  const [slug, setSlug] = createSignal('');
  const [categoryId, setCategoryId] = createSignal('');
  const [status, setStatus] = createSignal('DRAFT');
  const [content, setContent] = createSignal('');
  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');
  const [loaded, setLoaded] = createSignal(false);

  createEffect(() => {
    const value = article();
    if (!value || loaded()) return;
    setTitle(value.title || '');
    setSlug(value.slug || '');
    setCategoryId(value.category_id || '');
    setStatus(value.status || 'DRAFT');
    setContent(value.content || value.body || '');
    setLoaded(true);
  });

  const save = async (e: Event) => {
    e.preventDefault();
    try {
      setSaving(true);
      setError('');
      const res = await fetch(`${API}/api/admin/kb/articles/${params.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: title(),
          slug: slug(),
          category_id: categoryId() || null,
          status: status(),
          content: content(),
        }),
      });
      if (!res.ok) throw new Error('Failed to save article');
      navigate(`/admin/kb/articles/${params.id}`);
    } catch (err: any) {
      setError(err.message || 'Failed to save article');
    } finally {
      setSaving(false);
    }
  };

  return (
    <AdminShell>
      <div class="page-hero-card page-actions">
        <div>
          <h1 class="page-title">Edit KB Article</h1>
          <p class="page-subtitle">Update article metadata, status, and content.</p>
        </div>
        <div class="page-actions-right">
          <A class="btn" href={`/admin/kb/articles/${params.id}`}>Back to Detail</A>
          <A class="btn" href="/admin/kb/articles">Back to Articles</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() && loaded()}>
        <form class="card" onSubmit={save}>
          <div class="field-grid-2">
            <div class="field">
              <label>Title</label>
              <input value={title()} onInput={(e) => setTitle(e.currentTarget.value)} required />
            </div>
            <div class="field">
              <label>Slug</label>
              <input value={slug()} onInput={(e) => setSlug(e.currentTarget.value)} />
            </div>
            <div class="field">
              <label>Category ID</label>
              <input value={categoryId()} onInput={(e) => setCategoryId(e.currentTarget.value)} />
            </div>
            <div class="field">
              <label>Status</label>
              <select value={status()} onChange={(e) => setStatus(e.currentTarget.value)}>
                <option value="DRAFT">DRAFT</option>
                <option value="PUBLISHED">PUBLISHED</option>
              </select>
            </div>
            <div class="field" style="grid-column:1 / -1">
              <label>Content</label>
              <textarea rows="16" value={content()} onInput={(e) => setContent(e.currentTarget.value)} />
            </div>
          </div>

          <Show when={error()}>
            <p class="error-note">{error()}</p>
          </Show>

          <div class="actions" style="justify-content:flex-end">
            <button class="btn primary" type="submit" disabled={saving()}>
              {saving() ? 'Saving...' : 'Save Article'}
            </button>
          </div>
        </form>
      </Show>
    </AdminShell>
  );
}
