import Link from 'next/link'
import Image from 'next/image'
import { ArrowLeft, Clock, Calendar, Tag } from 'lucide-react'
import { notFound } from 'next/navigation'
import { POSTS } from '@/lib/blog-data'

// Placeholder content for each blog post
const POST_CONTENT: Record<string, string> = {
  'why-laravel-is-still-the-best-php-framework-in-2025': `
After building applications with Symfony, CodeIgniter, Yii, and Laravel over the past decade, I have seen frameworks come and go. Yet Laravel continues to dominate the PHP ecosystem, and for good reason.

## Developer Experience First

Laravel's philosophy has always been about making developers happy. The elegant syntax, expressive ORM (Eloquent), and comprehensive documentation make it a joy to work with. When you compare the time it takes to scaffold a new project in Laravel versus other frameworks, the difference is stark.

\`\`\`php
// Creating a model with migration, factory, and controller
php artisan make:model Product -mfc
\`\`\`

This single command generates four files that would take 15-20 minutes to write by hand. Multiply this across an entire project, and you save weeks of development time.

## The Ecosystem is Unmatched

Laravel is not just a framework; it is an ecosystem. You have:

- **Laravel Forge** for server provisioning
- **Laravel Vapor** for serverless deployment
- **Laravel Nova** for admin panels
- **Laravel Livewire** for reactive UIs without JavaScript
- **Laravel Sanctum** and **Passport** for API authentication

No other PHP framework offers this level of integration.

## Real-World Performance

Critics often claim Laravel is "slow," but in my experience deploying production applications serving millions of requests, performance has never been the bottleneck. With proper caching (Redis), queue management, and optimized database queries, Laravel applications perform exceptionally well.

## My Recommendation

If you are starting a new PHP project in 2025, Laravel should be your default choice unless you have a very specific reason to choose otherwise. The productivity gains, community support, and ecosystem make it the clear winner.
  `,
  'mern-stack-vs-nextjs-full-stack-which-should-you-choose': `
Having shipped production applications using both the traditional MERN stack (MongoDB, Express, React, Node) and Next.js full-stack approaches, I am often asked which one teams should choose. The answer, as always, is "it depends."

## The Traditional MERN Stack

The MERN stack gives you maximum flexibility. You have complete control over your backend architecture, API design, and deployment strategy. This is ideal when:

- You need a complex backend with multiple microservices
- Your API serves multiple clients (web, mobile, third-party)
- You have a dedicated backend team

\`\`\`javascript
// Traditional Express API endpoint
app.get('/api/users', async (req, res) => {
  const users = await User.find()
  res.json(users)
})
\`\`\`

## The Next.js Full-Stack Approach

Next.js has evolved into a complete full-stack framework. With API routes, server components, and server actions, you can build entire applications without a separate backend:

\`\`\`typescript
// Next.js Server Action
async function createUser(formData: FormData) {
  'use server'
  await db.user.create({ data: { name: formData.get('name') } })
}
\`\`\`

This is ideal when:

- You want faster development cycles
- Your team is primarily frontend-focused
- You are building a product with a single web client

## My Verdict

For startups and small teams, I recommend Next.js. The reduced complexity and deployment simplicity (especially with Vercel) outweigh the flexibility benefits of a separate backend. For larger organizations or API-first products, the traditional MERN stack still makes sense.
  `,
  'teaching-code-to-500-students-what-i-learned-about-learning': `
Over the past eight years at Broadway Infosys Nepal, I have trained over 500 students in web and mobile development. From complete beginners to experienced professionals looking to upskill, I have observed consistent patterns in how people learn technical skills.

## The Myth of "Programming Talent"

Many students arrive believing they either have or lack "programming talent." This is a myth. I have seen students who struggled with basic loops become excellent developers within months. The difference is not innate ability but consistent practice and the right mental framework.

## The 3 Stages of Technical Learning

### Stage 1: The Copy Phase

Beginners should start by copying. Follow tutorials exactly, type every line of code, and resist the urge to "improve" things. This builds muscle memory and pattern recognition.

### Stage 2: The Modify Phase

Once you can copy successfully, start modifying. Change colors, add features, break things intentionally to see what happens. This builds understanding.

### Stage 3: The Create Phase

Only after significant time in stages 1 and 2 should students attempt to build from scratch. By this point, they have internalized patterns and can focus on problem-solving rather than syntax.

## The Most Common Mistake

The biggest mistake I see is students jumping to Stage 3 too quickly. They watch one tutorial, then immediately try to build their own project. When they inevitably get stuck, they conclude they are "not cut out for programming."

## What Actually Works

- **Daily practice**: 1 hour every day beats 7 hours on weekends
- **Build real things**: Motivation comes from solving real problems
- **Teach others**: Explaining concepts solidifies understanding
- **Embrace confusion**: Feeling lost is part of the process

If you are learning to code, be patient with yourself. Every developer you admire was once confused by the same concepts that confuse you now.
  `,
  'flutter-vs-react-native-in-2024-a-developer-perspective': `
After shipping mobile applications in both Flutter and React Native, I have developed strong opinions about when to use each. Forget the benchmark charts and marketing materials—here is what actually matters in practice.

## Developer Experience

**React Native** feels familiar if you come from a web background. JSX, npm packages, and JavaScript/TypeScript are comfortable. However, debugging can be frustrating, and the infamous "red screen of death" appears more often than you would like.

**Flutter** requires learning Dart, which has a steeper initial learning curve. However, once you are comfortable, the developer experience is excellent. Hot reload is faster and more reliable, and the widget system is more predictable.

\`\`\`dart
// Flutter widget composition
Column(
  children: [
    Text('Hello'),
    ElevatedButton(onPressed: () {}, child: Text('Click')),
  ],
)
\`\`\`

## Performance

Both frameworks deliver near-native performance for most applications. Flutter has a slight edge in complex animations because it renders directly to a canvas rather than bridging to native components.

## Ecosystem and Packages

React Native has a larger ecosystem due to its longer history and access to npm packages. However, many packages are outdated or poorly maintained.

Flutter's package ecosystem is newer but more curated. The pub.dev scoring system helps identify high-quality packages.

## My Recommendation

Choose **React Native** if:
- Your team has strong web/JavaScript experience
- You need to share code with an existing React web app
- You are building a content-heavy app with standard UI patterns

Choose **Flutter** if:
- You are starting fresh without existing web code
- Your app has complex custom animations or UI
- Performance in graphics-intensive sections is critical

For my recent projects, I have leaned toward Flutter for new builds. The development speed and consistency across platforms have been worth the initial learning investment.
  `,
}

export async function generateStaticParams() {
  return POSTS.map((post) => ({ slug: post.slug }))
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = await params
  const post = POSTS.find((p) => p.slug === slug)
  if (!post) return { title: 'Post Not Found' }

  return {
    title: `${post.title} — Nitish Raj Uprety`,
    description: post.excerpt,
  }
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = await params
  const post = POSTS.find((p) => p.slug === slug)

  if (!post) {
    notFound()
  }

  const content = POST_CONTENT[slug] || ''

  return (
    <main className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b border-border">
        <div className="max-w-3xl mx-auto px-6 py-6 flex items-center justify-between">
          <Link
            href="/blog"
            className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
          >
            <ArrowLeft size={16} />
            All posts
          </Link>
        </div>
      </header>

      <article className="max-w-3xl mx-auto px-6 py-16">
        {/* Meta */}
        <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground mb-6">
          <span className="inline-flex items-center gap-1.5">
            <Calendar size={14} />
            {post.date}
          </span>
          <span className="inline-flex items-center gap-1.5">
            <Clock size={14} />
            {post.readTime}
          </span>
          <span className="inline-flex items-center gap-1.5 text-primary">
            <Tag size={14} />
            {post.tag}
          </span>
        </div>

        {/* Title */}
        <h1 className="font-serif text-3xl md:text-4xl font-bold text-foreground mb-6 text-balance leading-tight">
          {post.title}
        </h1>

        {/* Excerpt */}
        <p className="text-lg text-muted-foreground leading-relaxed mb-10 border-l-2 border-primary pl-4">
          {post.excerpt}
        </p>

        {/* Author */}
        <div className="flex items-center gap-4 pb-10 mb-10 border-b border-border">
          <div className="relative w-12 h-12 rounded-full overflow-hidden border border-border">
            <Image
              src="/images/nitish-profile.jpg"
              alt="Nitish Raj Uprety"
              fill
              className="object-cover object-top"
            />
          </div>
          <div>
            <p className="font-medium text-foreground">Nitish Raj Uprety</p>
            <p className="text-sm text-muted-foreground">
              Full-Stack Developer & Technical Trainer
            </p>
          </div>
        </div>

        {/* Content */}
        <div className="prose prose-neutral dark:prose-invert max-w-none prose-headings:font-serif prose-headings:font-semibold prose-h2:text-2xl prose-h2:mt-10 prose-h2:mb-4 prose-h3:text-lg prose-h3:mt-8 prose-h3:mb-3 prose-p:text-base prose-p:leading-relaxed prose-p:text-muted-foreground prose-strong:text-foreground prose-code:bg-secondary prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm prose-code:before:content-none prose-code:after:content-none prose-pre:bg-secondary prose-pre:border prose-pre:border-border prose-li:text-muted-foreground prose-ul:my-4 prose-ol:my-4">
          {content.split('\n\n').map((paragraph, idx) => {
            // Handle code blocks
            if (paragraph.includes('```')) {
              const codeMatch = paragraph.match(/```(\w+)?\n([\s\S]*?)```/)
              if (codeMatch) {
                return (
                  <pre
                    key={idx}
                    className="bg-secondary border border-border rounded-lg p-4 overflow-x-auto my-6"
                  >
                    <code className="text-sm text-foreground">
                      {codeMatch[2].trim()}
                    </code>
                  </pre>
                )
              }
            }

            // Handle headings
            if (paragraph.startsWith('## ')) {
              return (
                <h2
                  key={idx}
                  className="font-serif text-2xl font-semibold text-foreground mt-10 mb-4"
                >
                  {paragraph.replace('## ', '')}
                </h2>
              )
            }
            if (paragraph.startsWith('### ')) {
              return (
                <h3
                  key={idx}
                  className="font-serif text-lg font-semibold text-foreground mt-8 mb-3"
                >
                  {paragraph.replace('### ', '')}
                </h3>
              )
            }

            // Handle lists
            if (paragraph.startsWith('- ')) {
              const items = paragraph.split('\n').filter((line) => line.startsWith('- '))
              return (
                <ul key={idx} className="my-4 space-y-2">
                  {items.map((item, i) => (
                    <li key={i} className="text-muted-foreground">
                      {item.replace('- ', '').replace(/\*\*(.*?)\*\*/g, (_, text) => text)}
                    </li>
                  ))}
                </ul>
              )
            }

            // Regular paragraph
            if (paragraph.trim()) {
              return (
                <p
                  key={idx}
                  className="text-base text-muted-foreground leading-relaxed my-4"
                >
                  {paragraph.trim()}
                </p>
              )
            }

            return null
          })}
        </div>

        {/* Back link */}
        <div className="mt-16 pt-8 border-t border-border">
          <Link
            href="/blog"
            className="inline-flex items-center gap-2 text-sm text-primary hover:underline underline-offset-4"
          >
            <ArrowLeft size={16} />
            Back to all posts
          </Link>
        </div>
      </article>
    </main>
  )
}
