import { Component, createSignal, onMount } from 'solid-js';
import { useParams } from '@solidjs/router';
import { initAnalytics, trackPageView } from '../hooks/useAnalytics';
import Footer from '../components/Footer';

interface BlogPost {
  slug: string;
  title: string;
  excerpt: string | null;
  content: string;
  authorName: string | null;
  coverImageUrl: string | null;
  tags: string[];
  publishedAt: string;
  viewCount: number;
}

const BlogPostPage: Component = () => {
  const params = useParams();
  const [post, setPost] = createSignal<BlogPost | null>(null);
  const [loading, setLoading] = createSignal(true);
  const [notFound, setNotFound] = createSignal(false);

  onMount(async () => {
    initAnalytics();

    try {
      const res = await fetch(`/api/blog/${params.slug}`);
      if (res.ok) {
        const data = await res.json();
        setPost(data.post);
        trackPageView(`/blog/${params.slug}`, data.post.title);
      } else {
        setNotFound(true);
      }
    } catch {
      setNotFound(true);
    } finally {
      setLoading(false);
    }
  });

  return (
    <main>
      {loading() ? (
        <div class="blog-post-loading">
          <div class="container">
            <p>Loading article...</p>
          </div>
        </div>
      ) : notFound() || !post() ? (
        <div class="blog-post-not-found">
          <div class="container">
            <a href="/blog" class="back-link">← Back to Blog</a>
            <h1>Article Not Found</h1>
            <p>The article you're looking for doesn't exist or has been removed.</p>
          </div>
        </div>
      ) : (
        <>
          <article class="blog-post">
            <div class="container">
              <a href="/blog" class="back-link">← Back to Blog</a>
              <header class="blog-post-header">
                <h1>{post()!.title}</h1>
                <div class="blog-post-meta">
                  {post()!.authorName && <span>By {post()!.authorName}</span>}
                  {post()!.publishedAt && (
                    <span>{new Date(post()!.publishedAt).toLocaleDateString()}</span>
                  )}
                  <span>{post()!.viewCount} views</span>
                </div>
                {post()!.tags.length > 0 && (
                  <div class="blog-post-tags">
                    {post()!.tags.map((tag) => (
                      <span class="tag">{tag}</span>
                    ))}
                  </div>
                )}
              </header>
              {post()!.coverImageUrl && (
                <div class="blog-post-cover">
                  <img src={post()!.coverImageUrl} alt={post()!.title} />
                </div>
              )}
              <div class="blog-post-content" innerHTML={post()!.content} />
            </div>
          </article>
          <Footer />
        </>
      )}
    </main>
  );
};

export default BlogPostPage;
