import type { Metadata } from "next"
import Link from "next/link"
import { siteConfig, blogPosts } from "@/lib/data"
import { NewsletterPopup } from "@/components/blog/newsletter-popup"

export const metadata: Metadata = {
  title: "Blog",
  description: "Explore insights on AI research tools, document analysis, educational AI, and hallucination-free systems from the CodeframeAI team.",
}

export default async function BlogPage({ searchParams }: { searchParams: Promise<{ [key: string]: string | string[] | undefined }> }) {
  const resolvedParams = await searchParams;
  const q = typeof resolvedParams.q === 'string' ? resolvedParams.q.toLowerCase() : '';
  const categoryParam = typeof resolvedParams.category === 'string' ? resolvedParams.category : '';

  let filteredPosts = blogPosts;
  if (q) {
    filteredPosts = filteredPosts.filter(p => p.title.toLowerCase().includes(q) || p.excerpt.toLowerCase().includes(q));
  }
  if (categoryParam) {
    filteredPosts = filteredPosts.filter(p => p.category === categoryParam);
  }

  return (
    <div className="bg-[#f9fafb] min-h-screen">
      {/* Header Section */}
      <section 
        className="relative w-full h-[200px] flex items-center justify-center"
        style={{ backgroundColor: "#061e30" }}
      >
        <div className="absolute top-8 left-8 lg:left-16">
          <nav className="flex items-center gap-2 text-[15px] font-medium">
            <Link href="/" className="text-white hover:text-blue-400 transition-colors">
              Home
            </Link>
            <span className="text-gray-400">/</span>
            <span className="text-gray-400">Blogs</span>
          </nav>
        </div>
        
        <h1 className="text-4xl lg:text-[56px] font-bold text-white tracking-tight">
          Blogs
        </h1>
      </section>

      {/* Main Content Area */}
      <section className="py-12 overflow-x-hidden">
        <div className="max-w-[1400px] mx-auto px-4 lg:px-8">
          <div className="flex flex-col md:flex-row gap-8 lg:gap-10">
            {/* Blog Grid */}
            <div className="w-full md:w-[70%]">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredPosts.length === 0 && (
                  <div className="col-span-full text-center py-12 text-muted-foreground">
                    No blog posts found matching your search.
                  </div>
                )}
                {filteredPosts.map((post) => {
                  let pillColors = "bg-blue-50 text-blue-600 border-blue-200";
                  if (post.category === "AI Research Tools") {
                    pillColors = "bg-red-50 text-red-600 border-red-200";
                  } else if (post.category === "Technology") {
                    pillColors = "bg-green-50 text-green-600 border-green-200";
                  } else if (post.category === "AI / Education") {
                    pillColors = "bg-purple-50 text-purple-600 border-purple-200";
                  }

                  return (
                    <article
                      key={post.slug}
                      className="flex flex-col bg-card rounded-[20px] overflow-hidden border border-border shadow-sm hover:shadow-md transition-shadow"
                    >
                      <Link href={`/blog/${post.slug}`} className="block relative aspect-[1.5]">
                        <img 
                          src={post.image || "/placeholder.jpg"} 
                          alt={post.title}
                          className="object-cover w-full h-full"
                        />
                      </Link>

                      <div className="p-5 flex flex-col flex-1">
                        <div className="mb-3">
                          <span className={`inline-block px-3 py-1 text-[11px] font-bold uppercase tracking-wider rounded-md border ${pillColors}`}>
                            {post.category}
                          </span>
                        </div>

                        <Link href={`/blog/${post.slug}`}>
                          <h2 className="text-[18px] font-bold text-foreground leading-tight mb-2 hover:text-primary transition-colors">
                            {post.title}
                          </h2>
                        </Link>

                        <p className="text-[13px] text-muted-foreground leading-relaxed mb-4 line-clamp-3">
                          {post.excerpt}
                        </p>

                        <div className="mt-auto flex items-center gap-4 text-[11px] font-medium text-muted-foreground/70">
                          <span>{new Date(post.date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</span>
                          <span>{post.readTime}</span>
                        </div>
                      </div>
                    </article>
                  )
                })}
              </div>
            </div>

            {/* Sidebar */}
            <div className="w-full md:w-[350px] flex-shrink-0">
              <div className="flex flex-col gap-6">
                {/* Search */}
                <div className="bg-card rounded-[16px] border border-border p-7 shadow-sm">
                  <div className="relative mb-6 pb-3">
                    <h3 className="text-[18px] font-bold text-foreground">Search Blog</h3>
                    <div className="absolute bottom-0 left-0 w-full h-[2px] bg-primary/20" />
                    <div className="absolute bottom-0 left-0 w-12 h-[2px] bg-primary" />
                  </div>
                  <form action="/blog" method="GET" className="flex gap-0">
                    <input 
                      type="text"
                      name="q"
                      defaultValue={q}
                      placeholder="Search articles..." 
                      className="flex-1 min-w-0 bg-transparent border border-input rounded-l-md px-4 py-2.5 text-[14px] focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                    />
                    <button type="submit" className="bg-primary hover:bg-primary/90 text-primary-foreground px-5 py-2.5 text-[14px] font-medium rounded-r-md transition-colors">
                      Search
                    </button>
                  </form>
                </div>

                {/* Categories */}
                <div className="bg-card rounded-[16px] border border-border p-7 shadow-sm">
                  <div className="relative mb-6 pb-3">
                    <h3 className="text-[18px] font-bold text-foreground">Categories</h3>
                    <div className="absolute bottom-0 left-0 w-full h-[2px] bg-primary/20" />
                    <div className="absolute bottom-0 left-0 w-12 h-[2px] bg-primary" />
                  </div>
                  <div className="flex flex-col">
                    <Link 
                      href="/blog"
                      className={`flex items-center justify-between py-3.5 border-b border-border/50 last:border-0 hover:text-primary transition-colors group ${!categoryParam ? "text-primary" : ""}`}
                    >
                      <span className={`text-[14px] font-medium transition-colors group-hover:text-primary ${!categoryParam ? "text-primary" : "text-muted-foreground"}`}>
                        All Categories
                      </span>
                      <span className="text-muted-foreground/70 text-[13px]">
                        ({blogPosts.length})
                      </span>
                    </Link>
                    {Array.from(new Set(blogPosts.map(post => post.category))).map((cat) => (
                      <Link 
                        key={cat}
                        href={`/blog?category=${cat}`}
                        className={`flex items-center justify-between py-3.5 border-b border-border/50 last:border-0 hover:text-primary transition-colors group ${categoryParam === cat ? "text-primary" : ""}`}
                      >
                        <span className={`text-[14px] font-medium transition-colors group-hover:text-primary ${categoryParam === cat ? "text-primary" : "text-muted-foreground"}`}>
                          {cat}
                        </span>
                        <span className="text-muted-foreground/70 text-[13px]">
                          ({blogPosts.filter(p => p.category === cat).length})
                        </span>
                      </Link>
                    ))}
                  </div>
                </div>

                {/* Recent Posts */}
                <div className="bg-card rounded-[16px] border border-border p-7 shadow-sm">
                  <div className="relative mb-6 pb-3">
                    <h3 className="text-[18px] font-bold text-foreground">Recent Posts</h3>
                    <div className="absolute bottom-0 left-0 w-full h-[2px] bg-primary/20" />
                    <div className="absolute bottom-0 left-0 w-12 h-[2px] bg-primary" />
                  </div>
                  <div className="flex flex-col gap-5">
                    {[...blogPosts].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()).slice(0, 3).map((post) => (
                      <Link 
                        key={post.slug}
                        href={`/blog/${post.slug}`}
                        className="flex gap-4 group items-center"
                      >
                        <div className="relative h-[60px] w-[80px] shrink-0 overflow-hidden rounded-md border border-border">
                          <img 
                            src={post.image} 
                            alt={post.title}
                            className="h-full w-full object-cover"
                          />
                        </div>
                        <div className="flex flex-col gap-1 justify-center">
                          <h4 className="text-[13px] font-bold text-foreground group-hover:text-primary transition-colors leading-snug line-clamp-3">
                            {post.title}
                          </h4>
                          <span className="text-[11px] text-muted-foreground">
                            {new Date(post.date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}
                          </span>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>

                {/* Newsletter */}
                <NewsletterPopup />
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  )
}
