import Link from 'next/link';
import { ArrowUpRight, ArrowLeft, ArrowRight } from "@untitledui/icons";
import { Button, PhotoWithFallback, RoundButton } from '../elements';
import { Carousel } from '../elements/carousel/carousel-base';
import { cx } from '../../utils/cx';
import type { BlogPost } from '../../types/api/blog-post';

interface BlogHomeProps {
    blogPosts?: BlogPost[] | null;
    label?: string;
    title?: string;
    subtitle?: string;
    maxPosts?: number;
    viewAllHref?: string;
    viewAllText?: string;
}

export const BlogHome = ({
    blogPosts: postsData,
    label = "",
    title = "",
    subtitle = "",
    maxPosts = 6,
    viewAllHref = "/blog",
    viewAllText = "View all posts",
}: BlogHomeProps) => {
    
    const posts = Array.isArray(postsData) ? postsData.slice(0, maxPosts) : [];
    
    const formatDate = (dateString?: string) => {
        if (!dateString) return 'Recent';
        try {
            return new Date(dateString).toLocaleDateString('en-US', {
                day: 'numeric',
                month: 'short',
                year: 'numeric'
            });
        } catch {
            return 'Recent';
        }
    };

    return (
        <section className="overflow-hidden bg-primary py-16 md:py-24">
            <div className="mx-auto max-w-container px-4 md:px-8">
                <div className="flex flex-col items-start justify-between lg:flex-row">
                    <div className="max-w-3xl">
                        <p className="text-sm font-semibold text-brand-secondary md:text-md">{label}</p>
                        <h2 className="mt-3 text-display-sm font-semibold text-primary md:text-display-md">
                            {title}
                        </h2>
                        <p className="mt-4 text-lg text-tertiary md:mt-5 md:text-xl">
                            {subtitle}
                        </p>
                    </div>

                    {viewAllHref && (
                        <div className="hidden gap-3 lg:flex">
                            <Button size="xl" href={viewAllHref}>{viewAllText}</Button>
                        </div>
                    )}
                </div>

                {posts && posts.length > 0 ? (
                    <>
                        <Carousel.Root
                            className="mt-12 md:mt-16"
                            opts={{
                                align: "start",
                            }}
                        >
                            <Carousel.Content overflowHidden={false} className="gap-6 pr-4 md:gap-8 md:pr-8">
                                {posts.map((post, index) => {
                                    const author = post.blog_post_authors?.[0];
                                    const excerpt = post.excerpt_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
                                    
                                    return (
                                        <Carousel.Item key={post.id || index} className="max-w-xs md:max-w-96">
                                            <article className={cx("flex flex-col gap-4")}>
                                                <div className="relative">
                                                    <a href={`/blog/${post.slug || post.id}`} className="w-full" tabIndex={-1}>
                                                        <PhotoWithFallback
                                                            item={post}
                                                            fallbackId={post.id || index}
                                                            alt={post.title || 'Blog post'}
                                                            className={cx("aspect-[1.5] w-full object-cover")}
                                                        />
                                                    </a>
                                                    <div className="absolute inset-x-0 bottom-0 overflow-hidden bg-linear-to-b from-transparent to-black/40">
                                                        <div className="relative flex items-start justify-between bg-alpha-white/30 p-4 backdrop-blur-md before:absolute before:inset-x-0 before:top-0 before:h-px before:bg-alpha-white/30 md:p-5">
                                                            <div>
                                                                <a
                                                                    href={author?.slug ? `/blog/author/${author.slug}` : '/blog'}
                                                                    className="block rounded-xs text-sm font-semibold text-white outline-focus-ring focus-visible:outline-2 focus-visible:outline-offset-2"
                                                                >
                                                                    {author?.name || 'Author'}
                                                                </a>
                                                                <time className="block text-sm text-white">
                                                                    {formatDate(post.published_at)}
                                                                </time>
                                                            </div>
                                                            <Link
                                                                href="/blog"
                                                                className="rounded-xs text-sm font-semibold text-white outline-focus-ring focus-visible:outline-2 focus-visible:outline-offset-2"
                                                            >
                                                                Blog
                                                            </Link>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="flex flex-col gap-2">
                                                    <a
                                                        href={`/blog/${post.slug || post.id}`}
                                                        className="group/title flex justify-between gap-x-4 rounded-md text-lg font-semibold text-primary outline-focus-ring focus-visible:outline-2 focus-visible:outline-offset-2"
                                                    >
                                                        {post.title || 'Untitled Post'}
                                                        <ArrowUpRight
                                                            className="mt-0.5 size-6 shrink-0 text-fg-quaternary transition duration-100 ease-linear group-hover/title:text-fg-quaternary_hover"
                                                            aria-hidden="true"
                                                        />
                                                    </a>
                                                    {excerpt && (
                                                        <p className="line-clamp-2 text-md text-tertiary">{excerpt}</p>
                                                    )}
                                                </div>
                                            </article>
                                        </Carousel.Item>
                                    );
                                })}
                            </Carousel.Content>
                            <div className="mt-8 flex gap-4 md:gap-8">
                                <Carousel.PrevTrigger asChild>
                                    <RoundButton icon={ArrowLeft} />
                                </Carousel.PrevTrigger>
                                <Carousel.NextTrigger asChild>
                                    <RoundButton icon={ArrowRight} />
                                </Carousel.NextTrigger>
                            </div>
                        </Carousel.Root>
                        {viewAllHref && (
                            <div className="mt-12 flex flex-col gap-3 lg:hidden">
                                <Button size="xl" href={viewAllHref}>{viewAllText}</Button>
                            </div>
                        )}
                    </>
                ) : (
                    <div className="mt-12 text-center md:mt-16">
                        <p className="text-gray-500">No blog posts available</p>
                    </div>
                )}
            </div>
        </section>
    );
};
