'use client'

import Image from 'next/image'
import Link from 'next/link'
import { CalendarDays, ArrowRight, Tag } from 'lucide-react'
import { SectionWrapper } from '@/components/shared/section-wrapper'
import { createClient } from '@/lib/supabase/client'
import { useEffect, useState } from 'react'

interface BlogPost {
    id: string
    title: string
    slug: string
    excerpt: string
    cover_image: string | null
    category: string | null
    published_at: string | null
    tags: string[] | null
}

interface LatestInsightsProps {
    config?: {
        heading?: string
        subheading?: string
        post_count?: 3 | 4 | 6
        layout?: 'grid' | 'list'
    }
}

function formatDate(dateStr: string | null): string {
    if (!dateStr) return ''
    return new Date(dateStr).toLocaleDateString('en-US', {
        month: 'short', day: 'numeric', year: 'numeric'
    })
}

export function LatestInsights({ config }: LatestInsightsProps) {
    const heading = config?.heading || 'Latest Insights'
    const subheading = config?.subheading || 'Stay updated with our latest articles and tutorials'
    const postCount = config?.post_count || 3
    const layout = config?.layout || 'grid'

    const [posts, setPosts] = useState<BlogPost[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const supabase = createClient()
        supabase
            .from('blog_posts')
            .select('id, title, slug, excerpt, cover_image, category, published_at, tags')
            .eq('status', 'published')
            .order('published_at', { ascending: false })
            .limit(postCount)
            .then(({ data }) => {
                setPosts((data as BlogPost[]) || [])
                setLoading(false)
            })
    }, [postCount])

    if (loading) return null
    if (posts.length === 0) return null

    return (
        <SectionWrapper bg="lavender">
            <div className="text-center mb-12">
                <h2 className="text-3xl md:text-4xl font-bold text-navy mb-4">{heading}</h2>
                {subheading && <p className="text-slate-600 max-w-2xl mx-auto">{subheading}</p>}
            </div>

            {layout === 'grid' ? (
                <div className={`grid grid-cols-1 md:grid-cols-${postCount <= 3 ? postCount : 3} gap-8 max-w-6xl mx-auto`}>
                    {posts.map(post => (
                        <Link key={post.id} href={`/blog/${post.slug}`} className="group">
                            <article className="bg-white rounded-2xl overflow-hidden border border-slate-100 shadow-sm hover:shadow-xl transition-all duration-300 hover:-translate-y-1 h-full flex flex-col">
                                {/* Cover image */}
                                <div className="relative h-48 overflow-hidden bg-slate-100">
                                    {post.cover_image ? (
                                        <Image
                                            src={post.cover_image}
                                            alt={post.title}
                                            fill
                                            sizes="(max-width: 768px) 100vw, 33vw"
                                            className="object-cover group-hover:scale-105 transition-transform duration-500"
                                        />
                                    ) : (
                                        <div className="w-full h-full bg-gradient-to-br from-navy/10 to-brand-orange/10 flex items-center justify-center">
                                            <span className="text-4xl opacity-20">📝</span>
                                        </div>
                                    )}
                                    {post.category && (
                                        <span className="absolute top-3 left-3 px-3 py-1 bg-white/90 backdrop-blur-sm text-navy text-xs font-bold rounded-full flex items-center gap-1.5">
                                            <Tag className="h-3 w-3" />
                                            {post.category}
                                        </span>
                                    )}
                                </div>

                                {/* Content */}
                                <div className="p-6 flex-1 flex flex-col">
                                    {post.published_at && (
                                        <div className="flex items-center gap-1.5 text-xs text-slate-400 mb-3">
                                            <CalendarDays className="h-3.5 w-3.5" />
                                            {formatDate(post.published_at)}
                                        </div>
                                    )}
                                    <h3 className="text-lg font-bold text-navy mb-2 line-clamp-2 group-hover:text-brand-orange transition-colors">
                                        {post.title}
                                    </h3>
                                    {post.excerpt && (
                                        <p className="text-sm text-slate-500 leading-relaxed line-clamp-3 flex-1">
                                            {post.excerpt}
                                        </p>
                                    )}
                                    <div className="flex items-center gap-1 text-sm font-semibold text-brand-orange mt-4 group-hover:gap-2 transition-all">
                                        Read More <ArrowRight className="h-4 w-4" />
                                    </div>
                                </div>
                            </article>
                        </Link>
                    ))}
                </div>
            ) : (
                <div className="max-w-4xl mx-auto space-y-6">
                    {posts.map(post => (
                        <Link key={post.id} href={`/blog/${post.slug}`} className="group">
                            <article className="bg-white rounded-2xl overflow-hidden border border-slate-100 shadow-sm hover:shadow-lg transition-all duration-300 flex flex-col md:flex-row">
                                <div className="relative w-full md:w-64 h-48 md:h-auto overflow-hidden bg-slate-100 shrink-0">
                                    {post.cover_image ? (
                                        <Image
                                            src={post.cover_image}
                                            alt={post.title}
                                            fill
                                            sizes="256px"
                                            className="object-cover group-hover:scale-105 transition-transform duration-500"
                                        />
                                    ) : (
                                        <div className="w-full h-full bg-gradient-to-br from-navy/10 to-brand-orange/10 flex items-center justify-center">
                                            <span className="text-4xl opacity-20">📝</span>
                                        </div>
                                    )}
                                </div>
                                <div className="p-6 flex-1">
                                    <div className="flex items-center gap-3 mb-3">
                                        {post.category && (
                                            <span className="px-2.5 py-0.5 bg-navy/5 text-navy text-xs font-bold rounded-full">
                                                {post.category}
                                            </span>
                                        )}
                                        {post.published_at && (
                                            <span className="flex items-center gap-1.5 text-xs text-slate-400">
                                                <CalendarDays className="h-3.5 w-3.5" />
                                                {formatDate(post.published_at)}
                                            </span>
                                        )}
                                    </div>
                                    <h3 className="text-xl font-bold text-navy mb-2 group-hover:text-brand-orange transition-colors">
                                        {post.title}
                                    </h3>
                                    {post.excerpt && (
                                        <p className="text-sm text-slate-500 leading-relaxed line-clamp-2">
                                            {post.excerpt}
                                        </p>
                                    )}
                                    <div className="flex items-center gap-1 text-sm font-semibold text-brand-orange mt-3 group-hover:gap-2 transition-all">
                                        Read More <ArrowRight className="h-4 w-4" />
                                    </div>
                                </div>
                            </article>
                        </Link>
                    ))}
                </div>
            )}

            {/* View All Link */}
            <div className="text-center mt-10">
                <Link href="/blog" className="inline-flex items-center gap-2 text-sm font-semibold text-navy hover:text-brand-orange transition-colors group">
                    View All Articles
                    <ArrowRight className="h-4 w-4 group-hover:translate-x-1 transition-transform" />
                </Link>
            </div>
        </SectionWrapper>
    )
}
