'use client'

import { useState } from 'react'

import { useRouter } from 'next/navigation'

import { SearchIcon, ArrowRightIcon, CalendarDaysIcon } from 'lucide-react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator
} from '@/components/ui/breadcrumb'

// Import the blog posts data from centralized location
import { blogPosts } from '@/assets/data/blog-posts'

export type BlogPost = {
  id: number
  slug: string
  title: string
  description: string
  imageUrl: string
  imageAlt: string
  date: string
  category: string
  author: string
  avatarUrl: string
  readTime: number
  featured: boolean
}

// Simply use all blog posts since they already have correct slugs and correspond to existing pages
const getAvailableBlogPosts = () => {
  return blogPosts
}

const BlogGrid = ({ posts, onCategoryClick }: { posts: BlogPost[]; onCategoryClick: (category: string) => void }) => {
  const router = useRouter()

  const handleCardClick = (post: BlogPost) => {
    // Navigate to individual blog pages using the slug
    router.push(`/blog-detail/${post.slug}`)
  }

  return (
    <div className='grid gap-6 sm:grid-cols-2 lg:grid-cols-3'>
      {posts.map(post => (
        <Card
          key={post.id}
          className='group h-full cursor-pointer overflow-hidden shadow-none transition-all duration-300'
          onClick={() => handleCardClick(post)}
        >
          <CardContent className='space-y-3.5'>
            <div className='mb-6 overflow-hidden rounded-lg sm:mb-12'>
              <img
                src={post.imageUrl}
                alt={post.imageAlt}
                className='h-59.5 w-full object-cover transition-transform duration-300 group-hover:scale-105'
              />
            </div>
            <div className='flex items-center justify-between gap-1.5'>
              <div className='text-muted-foreground flex items-center gap-1.5'>
                <CalendarDaysIcon className='size-5' />
                <span>{post.date}</span>
              </div>
              <Badge
                className='bg-primary/10 text-primary rounded-full border-0 text-sm'
                onClick={e => {
                  e.stopPropagation()
                  onCategoryClick(post.category)
                  router.push(`/#category-${post.category}`)
                }}
              >
                {post.category}
              </Badge>
            </div>
            <h3 className='line-clamp-2 text-lg font-medium md:text-xl'>{post.title}</h3>
            <p className='text-muted-foreground line-clamp-2'>{post.description}</p>
            <div className='flex items-center justify-between'>
              <span className='text-sm font-medium'>{post.author}</span>
              <Button
                size='icon'
                className='group-hover:bg-primary! bg-background text-foreground hover:bg-primary! hover:text-primary-foreground group-hover:text-primary-foreground border group-hover:border-transparent hover:border-transparent'
              >
                <ArrowRightIcon className='size-4 -rotate-45' />
                <span className='sr-only'>Read more: {post.title}</span>
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

const Blog = () => {
  const [selectedTab, setSelectedTab] = useState('All')
  const router = useRouter()

  // Get only the blog posts that have corresponding pages
  const availableBlogPosts = getAvailableBlogPosts()

  // Filter out featured posts to avoid duplication with hero section
  // Sort posts by ID in descending order (newest first)
  const nonFeaturedPosts = availableBlogPosts.filter(post => !post.featured).sort((a, b) => b.id - a.id)

  // Dynamically generate categories from the available data
  const uniqueCategories = [...new Set(nonFeaturedPosts.map(post => post.category))]
  const categories = ['All', ...uniqueCategories.sort()]

  const handleTabChange = (tab: string) => {
    setSelectedTab(tab)

    if (tab === 'All') {
      router.push('#categories')
    }
  }

  return (
    <section className='py-8 sm:py-16 lg:py-24' id='categories'>
      <div className='mx-auto max-w-7xl space-y-8 px-4 sm:px-6 lg:space-y-16 lg:px-8'>
        {/* Header */}
        <div className='space-y-4'>
          {selectedTab === 'All' && <p className='text-sm'>Blogs</p>}
          {selectedTab !== 'All' && (
            <Breadcrumb>
              <BreadcrumbList>
                <BreadcrumbItem>
                  <BreadcrumbLink href='#'>Blog</BreadcrumbLink>
                </BreadcrumbItem>
                <BreadcrumbSeparator />
                <BreadcrumbItem>
                  <BreadcrumbPage>{selectedTab}</BreadcrumbPage>
                </BreadcrumbItem>
              </BreadcrumbList>
            </Breadcrumb>
          )}

          <h2 className='text-2xl font-semibold md:text-3xl lg:text-4xl'>
            Build Better Products with Insights & Inspiration.
          </h2>

          <p className='text-muted-foreground text-lg md:text-xl'>
            Practical insights and real stories to guide your product from vision to reality.
          </p>
        </div>

        {/* Tabs and Search */}
        <Tabs defaultValue='All' value={selectedTab} onValueChange={handleTabChange} className='gap-8 lg:gap-16'>
          <div className='flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center'>
            <ScrollArea className='bg-muted w-full rounded-lg sm:w-auto'>
              <TabsList className='h-auto gap-1'>
                {categories.map(category => (
                  <TabsTrigger
                    key={category}
                    value={category}
                    id={`category-${category}`}
                    className='hover:bg-primary/10 cursor-pointer rounded-lg px-4 text-base'
                  >
                    {category}
                  </TabsTrigger>
                ))}
              </TabsList>
              <ScrollBar orientation='horizontal' />
            </ScrollArea>

            <div className='relative max-md:w-full'>
              <div className='text-muted-foreground pointer-events-none absolute inset-y-0 left-0 flex items-center justify-center pl-3 peer-disabled:opacity-50'>
                <SearchIcon className='size-4' />
                <span className='sr-only'>Search</span>
              </div>
              <Input
                type='search'
                placeholder='Search'
                className='peer h-10 px-9 [&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none [&::-webkit-search-results-button]:appearance-none [&::-webkit-search-results-decoration]:appearance-none'
              />
            </div>
          </div>

          {/* All Posts Tab */}
          <TabsContent value='All'>
            <BlogGrid posts={nonFeaturedPosts} onCategoryClick={handleTabChange} />
          </TabsContent>

          {/* Category-specific Tabs */}
          {categories.slice(1).map((category, index) => (
            <TabsContent key={index} value={category}>
              <BlogGrid
                posts={nonFeaturedPosts.filter(post => post.category === category)}
                onCategoryClick={handleTabChange}
              />
            </TabsContent>
          ))}
        </Tabs>
      </div>
    </section>
  )
}

export default Blog
