import type { Metadata } from "next"
import Link from "next/link"
import { notFound } from "next/navigation"
import { siteConfig, blogPosts } from "@/lib/data"
import { blogContent } from "@/lib/blog-content"
import { Calendar, Clock, User } from "lucide-react"
import { Button } from "@/components/ui/button"
import { NewsletterPopup } from "@/components/blog/newsletter-popup"

interface BlogPageProps {
  params: Promise<{ slug: string }>
}

export async function generateStaticParams() {
  return blogPosts.map((post) => ({
    slug: post.slug,
  }))
}

export async function generateMetadata({ params }: BlogPageProps): Promise<Metadata> {
  const { slug } = await params
  const content = blogContent[slug as keyof typeof blogContent]
  
  if (!content) {
    return {
      title: "Blog Post Not Found",
    }
  }

  return {
    title: content.title,
    description: content.metaDescription,
    keywords: content.keywords,
    authors: [{ name: content.author }],
    openGraph: {
      title: `${content.title} | ${siteConfig.name}`,
      description: content.metaDescription,
      url: `${siteConfig.url}/blog/${slug}`,
      siteName: siteConfig.name,
      type: "article",
      publishedTime: content.date,
      authors: [content.author],
    },
    twitter: {
      card: "summary_large_image",
      title: content.title,
      description: content.metaDescription,
    },
    alternates: {
      canonical: `${siteConfig.url}/blog/${slug}`,
    },
  }
}

export default async function BlogArticlePage({ params }: BlogPageProps) {
  const { slug } = await params
  const content = blogContent[slug as keyof typeof blogContent]
  const postMeta = blogPosts.find(p => p.slug === slug)
  
  if (!content || !postMeta) {
    notFound()
  }

  const parseMarkdown = (text: string) => {
    // Basic bold parsing: **text** -> strong
    const parts = text.split(/(\*\*.*?\*\*)/g);
    return parts.map((part, i) => {
      if (part.startsWith('**') && part.endsWith('**')) {
        return <strong key={i} className="font-bold text-foreground">{part.slice(2, -2)}</strong>;
      }
      return part;
    });
  };

  const renderContent = (text: string) => {
    const lines = text.trim().split('\n');
    const elements = [];
    let inTable = false;
    let tableHeaders: string[] = [];
    let tableRows: string[][] = [];

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const trimmed = line.trim();

      if (trimmed.startsWith('|') && trimmed.endsWith('|')) {
        if (!inTable) {
          inTable = true;
          // Extract headers
          tableHeaders = trimmed.split('|').filter(s => s.trim() !== '').map(s => s.trim());
          // Skip the next line which is the separator (e.g., |---|---|)
          i++; 
          continue;
        } else {
          // Extract row data
          tableRows.push(trimmed.split('|').filter(s => s !== '').map(s => s.trim()));
          continue;
        }
      } else if (inTable) {
        // Table is finished, render it
        elements.push(
          <div key={`table-${i}`} className="my-6 overflow-x-auto rounded-lg border border-border">
            <table className="w-full text-sm text-left">
              <thead className="bg-muted/50 text-muted-foreground uppercase text-xs">
                <tr>
                  {tableHeaders.map((header, idx) => (
                    <th key={idx} className="px-4 py-3 font-medium border-b border-border">{header}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {tableRows.map((row, rIdx) => (
                  <tr key={rIdx} className="hover:bg-muted/30 transition-colors">
                    {row.map((cell, cIdx) => (
                      <td key={cIdx} className="px-4 py-3 text-foreground">{parseMarkdown(cell)}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );
        inTable = false;
        tableHeaders = [];
        tableRows = [];
      }

      // Normal parsing
      if (line.startsWith('## ')) {
        elements.push(<h2 key={i} className="text-[20px] font-bold text-foreground mt-8 mb-4">{line.replace('## ', '')}</h2>);
      }
      else if (line.startsWith('### ')) {
        elements.push(<h3 key={i} className="text-[16px] font-bold text-foreground mt-6 mb-3">{line.replace('### ', '')}</h3>);
      }
      else if (trimmed.match(/^[-*]\s/)) {
        elements.push(
          <div key={i} className="flex gap-3 ml-6 mb-2 items-start">
            <span className="h-1.5 w-1.5 rounded-full bg-primary mt-2 shrink-0" />
            <div className="text-muted-foreground text-[14.5px] leading-snug">{parseMarkdown(trimmed.replace(/^[-*]\s/, ''))}</div>
          </div>
        );
      }
      else if (trimmed.match(/^\d+\.\s/)) {
        const match = trimmed.match(/^(\d+\.)\s/);
        elements.push(
          <div key={i} className="flex gap-3 ml-6 mb-2 items-start">
            <span className="text-primary font-bold text-[14.5px] leading-snug shrink-0">{match ? match[1] : ''}</span>
            <div className="text-muted-foreground text-[14.5px] leading-snug">{parseMarkdown(trimmed.replace(/^\d+\.\s/, ''))}</div>
          </div>
        );
      }
      else if (trimmed === '') {
        // Skip empty lines to remove extra spaces
        continue;
      }
      else {
        elements.push(<p key={i} className="mb-4 text-[15px] leading-relaxed text-muted-foreground">{parseMarkdown(line)}</p>);
      }
    }

    // In case the file ends with a table
    if (inTable) {
      elements.push(
        <div key={`table-end`} className="my-6 overflow-x-auto rounded-lg border border-border">
          <table className="w-full text-sm text-left">
            <thead className="bg-muted/50 text-muted-foreground uppercase text-xs">
              <tr>
                {tableHeaders.map((header, idx) => (
                  <th key={idx} className="px-4 py-3 font-medium border-b border-border">{header}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {tableRows.map((row, rIdx) => (
                <tr key={rIdx} className="hover:bg-muted/30 transition-colors">
                  {row.map((cell, cIdx) => (
                    <td key={cIdx} className="px-4 py-3 text-foreground">{parseMarkdown(cell)}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }

    return elements;
  };


  return (
    <div className="bg-background min-h-screen">
      {/* Header Section */}
      <section className="relative w-full py-6 flex items-center justify-center min-h-[120px] bg-gradient-to-br from-primary/5 via-background to-accent/5 border-b border-border">
        <div className="absolute top-4 left-4 lg:left-8">
          <nav className="flex items-center gap-2 text-[13px] font-medium">
            <Link href="/" className="text-primary hover:underline">
              Home
            </Link>
            <span className="text-muted-foreground">/</span>
            <Link href="/blog" className="text-primary hover:underline">
              Blogs
            </Link>
            <span className="text-muted-foreground">/</span>
            <span className="text-muted-foreground/70 truncate max-w-[150px]">{content.title}</span>
          </nav>
        </div>
        
        <div className="max-w-4xl mx-auto px-4 text-center mt-5">
          <h1 className="text-xl lg:text-2xl font-bold text-foreground tracking-tight leading-tight">
            {content.title}
          </h1>
        </div>
      </section>

      {/* Main Content Area */}
      <section className="pt-4 pb-8 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">
            {/* Main Content Column */}
            <div className="w-full md:w-[70%]">
              <article className="bg-card rounded-[16px] p-5 md:p-6 border border-border shadow-sm h-full">
                {/* Meta Info */}
                <div className="flex flex-wrap items-center gap-5 text-[12px] text-muted-foreground mb-4 pb-4 border-b border-border/50">
                  <span className="flex items-center gap-1.5">
                    <User className="h-3.5 w-3.5 text-primary" />
                    {content.author}
                  </span>
                  <span className="flex items-center gap-1.5">
                    <Calendar className="h-3.5 w-3.5 text-primary" />
                    {new Date(content.date).toLocaleDateString('en-US', { 
                      month: 'short', 
                      day: 'numeric', 
                      year: 'numeric' 
                    })}
                  </span>
                  <span className="flex items-center gap-1.5">
                    <Clock className="h-3.5 w-3.5 text-primary" />
                    {content.readTime}
                  </span>
                </div>

                {/* Featured Image */}
                {postMeta.image && (
                  <div className="relative w-full overflow-hidden rounded-xl border border-border/50 mb-5">
                    <img 
                      src={postMeta.image} 
                      alt={content.title}
                      className="w-full h-auto"
                    />
                  </div>
                )}

                {/* Plain Blog Content */}
                <div className="text-foreground leading-relaxed">
                  {renderContent(content.content)}
                </div>

                {/* Share Section */}
                <div className="mt-8 pt-4 border-t border-border/50">
                  <h3 className="text-[12px] font-bold uppercase tracking-wider text-foreground mb-3">Share This Post</h3>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" className="rounded-md px-4 border-border hover:bg-primary hover:text-primary-foreground hover:border-primary transition-all h-8 text-[12px]" asChild>
                      <a 
                        href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(content.title)}&url=${encodeURIComponent(`${siteConfig.url}/blog/${slug}`)}`}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        Twitter
                      </a>
                    </Button>
                    <Button variant="outline" size="sm" className="rounded-md px-4 border-border hover:bg-primary hover:text-primary-foreground hover:border-primary transition-all h-8 text-[12px]" asChild>
                      <a 
                        href={`https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(`${siteConfig.url}/blog/${slug}`)}&title=${encodeURIComponent(content.title)}`}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        LinkedIn
                      </a>
                    </Button>
                  </div>
                </div>
              </article>
            </div>

            {/* Sidebar */}
            <div className="w-full md:w-[30%] flex-shrink-0">
              <div className="flex flex-col gap-6">
                {/* Search */}
                <div className="bg-card rounded-[16px] border border-border p-5 shadow-sm">
                  <div className="relative mb-5 pb-2.5">
                    <h3 className="text-[16px] font-bold text-foreground">Search Blog</h3>
                    <div className="absolute bottom-0 left-0 w-full h-[1px] bg-primary/20" />
                    <div className="absolute bottom-0 left-0 w-10 h-[1px] bg-primary" />
                  </div>
                  <form action="/blog" method="GET" className="flex gap-0">
                    <input 
                      type="text"
                      name="q"
                      placeholder="Search..." 
                      className="flex-1 min-w-0 bg-transparent border border-input rounded-l-md px-3 py-2 text-[13px] 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-4 py-2 text-[13px] font-medium rounded-r-md transition-colors">
                      Search
                    </button>
                  </form>
                </div>

                {/* Categories */}
                <div className="bg-card rounded-[16px] border border-border p-5 shadow-sm">
                  <div className="relative mb-5 pb-2.5">
                    <h3 className="text-[16px] font-bold text-foreground">Categories</h3>
                    <div className="absolute bottom-0 left-0 w-full h-[1px] bg-primary/20" />
                    <div className="absolute bottom-0 left-0 w-10 h-[1px] bg-primary" />
                  </div>
                  <div className="flex flex-col">
                    <Link 
                      href="/blog"
                      className="flex items-center justify-between py-2.5 border-b border-border/50 last:border-0 hover:text-primary transition-colors group"
                    >
                      <span className="text-muted-foreground group-hover:text-primary text-[13px] font-medium transition-colors">
                        All Categories
                      </span>
                      <span className="text-muted-foreground/70 text-[12px]">
                        ({blogPosts.length})
                      </span>
                    </Link>
                    {Array.from(new Set(blogPosts.map(post => post.category))).map((category) => (
                      <Link 
                        key={category}
                        href={`/blog?category=${category}`}
                        className={`flex items-center justify-between py-2.5 border-b border-border/50 last:border-0 hover:text-primary transition-colors group ${postMeta.category === category ? "text-primary" : ""}`}
                      >
                        <span className={`text-[13px] font-medium transition-colors group-hover:text-primary ${postMeta.category === category ? "text-primary" : "text-muted-foreground"}`}>
                          {category}
                        </span>
                        <span className="text-muted-foreground/70 text-[12px]">
                          ({blogPosts.filter(p => p.category === category).length})
                        </span>
                      </Link>
                    ))}
                  </div>
                </div>

                {/* Recent Posts */}
                <div className="bg-card rounded-[16px] border border-border p-5 shadow-sm">
                  <div className="relative mb-5 pb-2.5">
                    <h3 className="text-[16px] font-bold text-foreground">Recent Posts</h3>
                    <div className="absolute bottom-0 left-0 w-full h-[1px] bg-primary/20" />
                    <div className="absolute bottom-0 left-0 w-10 h-[1px] bg-primary" />
                  </div>
                  <div className="flex flex-col gap-4">
                    {[...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-3 group items-center"
                      >
                        <div className="relative h-[48px] w-[64px] 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-0.5 justify-center">
                          <h4 className="text-[12px] font-bold text-foreground group-hover:text-primary transition-colors leading-tight line-clamp-2">
                            {post.title}
                          </h4>
                          <span className="text-[10px] text-muted-foreground">
                            {new Date(post.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                          </span>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>

                {/* Newsletter */}
                <NewsletterPopup />
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  )
}
