import { FC, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import BlogCard from '../components/blog/BlogCard';
import styles from './Blog.module.css';
import matter from 'gray-matter';
import { Buffer } from 'buffer';

// Make Buffer available globally
(globalThis as any).Buffer = Buffer;

interface BlogPost {
  title: string;
  date: string;
  excerpt: string;
  content: string;
  slug: string;
}

interface GroupedPosts {
  [year: string]: {
    [month: string]: BlogPost[];
  };
}

const Blog: FC = () => {
  const { slug } = useParams<{ slug: string }>();
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [groupedPosts, setGroupedPosts] = useState<GroupedPosts>({});
  const [currentPost, setCurrentPost] = useState<BlogPost | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadPosts = async () => {
      try {
        setLoading(true);
        console.log('Starting to load posts...');
        
        // Import all markdown files
        const postModules = import.meta.glob('../content/blog/*.md', { 
          query: '?raw',
          import: 'default'
        });
        
        console.log('Found post modules:', Object.keys(postModules));
        
        const loadedPosts = await Promise.all(
          Object.entries(postModules).map(async ([path, getContent]) => {
            console.log('Loading content from:', path);
            const content = await getContent();
            const { data, content: markdownContent } = matter(content);
            const slug = path.split('/').pop()?.replace('.md', '') || '';
            
            console.log('Loaded post:', { path, slug, data });
            
            return {
              ...data,
              content: markdownContent,
              slug,
            } as BlogPost;
          })
        );

        console.log('All posts loaded:', loadedPosts);

        const sortedPosts = loadedPosts.sort(
          (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
        );

        setPosts(sortedPosts);
        
        // Group posts by year and month
        const grouped: GroupedPosts = {};
        sortedPosts.forEach(post => {
          const date = new Date(post.date);
          const year = date.getFullYear().toString();
          const month = date.toLocaleString('default', { month: 'long' });
          
          if (!grouped[year]) {
            grouped[year] = {};
          }
          if (!grouped[year][month]) {
            grouped[year][month] = [];
          }
          
          grouped[year][month].push(post);
        });
        
        console.log('Grouped posts:', grouped);
        setGroupedPosts(grouped);
        
        if (slug) {
          const post = sortedPosts.find(p => p.slug === slug);
          if (post) setCurrentPost(post);
        }
      } catch (error) {
        console.error('Error loading blog posts:', error);
      } finally {
        setLoading(false);
      }
    };

    loadPosts();
  }, [slug]);

  if (loading) {
    return (
      <div className={styles.loading}>
        <h1>Loading...</h1>
      </div>
    );
  }

  if (slug && currentPost) {
    return (
      <div className={styles.blogPost}>
        <article>
          <h1>{currentPost.title}</h1>
          <time>{new Date(currentPost.date).toLocaleDateString()}</time>
          <div className={styles.content}>
            <ReactMarkdown>{currentPost.content}</ReactMarkdown>
          </div>
        </article>
      </div>
    );
  }

  return (
    <div className={styles.blogList}>
      <h1>Blog Posts</h1>
      <div className={styles.timeline}>
        {Object.entries(groupedPosts).map(([year, months]) => (
          <div key={year} className={styles.yearGroup}>
            <h2 className={styles.year}>{year}</h2>
            {Object.entries(months).map(([month, posts]) => (
              <div key={`${year}-${month}`} className={styles.monthGroup}>
                <h3 className={styles.month}>{month}</h3>
                <div className={styles.posts}>
                  {posts.map((post) => (
                    <BlogCard key={post.slug} post={post} />
                  ))}
                </div>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Blog; 