"use client";

import React, { useState } from 'react';
import { ArrowUpRight } from '@untitledui/icons';
import { Avatar, Select, SelectItem, PaginationPageDefault, PhotoWithFallback } from '../elements';
import { BlogCardVertical } from './blog-cards';
import { useBreakpoint } from '../../lib/hooks/use-breakpoint';
import { cx } from '../../utils/cx';
import { getAvatarUrl } from '../../utils/photo-helpers';
import type { BlogPost } from '../../types/api/blog-post';

interface BlogGalleryProps {
    blogPosts?: BlogPost[] | null;
    postsPerPage?: number;
    className?: string;
}

const defaultSortByOptions = [
    { id: "recent", label: "Most recent" },
    { id: "popular", label: "Most popular" },
    { id: "viewed", label: "Most viewed" },
];

export const BlogGallery = ({
    blogPosts: postsData,
    postsPerPage = 12,
    className = "",
}: BlogGalleryProps) => {
    const sortByOptions = defaultSortByOptions;

    const posts = Array.isArray(postsData) ? postsData : [];
    const isDesktop = useBreakpoint("lg");
    const [currentPage, setCurrentPage] = useState(1);
    const [sortBy, setSortBy] = useState(sortByOptions[0].id);

    // Sort posts based on sortBy
    const sortedPosts = [...posts];
    if (sortBy === 'recent') {
        sortedPosts.sort((a, b) => {
            const dateA = a.published_at ? new Date(a.published_at).getTime() : 0;
            const dateB = b.published_at ? new Date(b.published_at).getTime() : 0;
            return dateB - dateA;
        });
    }
    // TODO: Add popular and viewed sorting when those fields are available

    // Get featured post (first post with featured: true or first post)
    const featuredPost = sortedPosts.find((post) => post.featured) || sortedPosts[0];
    const nonFeaturedPosts = sortedPosts.filter((post) => post.id !== featuredPost?.id);
    
    // Calculate pagination for non-featured posts
    const totalPages = Math.ceil(nonFeaturedPosts.length / postsPerPage);
    const startIndex = (currentPage - 1) * postsPerPage;
    const endIndex = startIndex + postsPerPage;
    const paginatedNonFeaturedPosts = nonFeaturedPosts.slice(startIndex, endIndex);

    // Reset to page 1 when sort changes
    React.useEffect(() => {
        setCurrentPage(1);
    }, [sortBy]);

    return (
        <section className={className}>
            <div className="mx-auto flex w-full max-w-container flex-col gap-12 px-4 md:gap-16 md:px-8">
                {posts.length > 0 ? (
                    <>
                        {/* Featured Post - Desktop */}
                        {featuredPost && (
                            <a
                                href={`/blog/${featuredPost.slug}`}
                                className="relative hidden w-full overflow-hidden rounded-2xl outline-focus-ring select-none focus:outline-2 focus:outline-offset-4 md:block md:h-145 lg:h-180"
                            >
                                <PhotoWithFallback
                                    item={featuredPost}
                                    fallbackId={featuredPost.id}
                                    alt={featuredPost.title || 'Featured post'}
                                    className="absolute inset-0 size-full object-cover"
                                />

                                {featuredPost && (() => {
                                    const author = Array.isArray(featuredPost.blog_post_authors) && featuredPost.blog_post_authors.length > 0 
                                        ? featuredPost.blog_post_authors[0] 
                                        : null;
                                    const authorName = author?.name || 'Author';
                                    const authorAvatarUrl = getAvatarUrl(author?.photo_attachments, author?.id, authorName);
                                    const publishedAt = featuredPost.published_at 
                                        ? new Date(featuredPost.published_at).toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' })
                                        : 'Recent';
                                    const summary = featuredPost.excerpt_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
                                    
                                    return (
                                        <div className="absolute inset-x-0 bottom-0 w-full bg-linear-to-t from-black/40 to-transparent pt-24">
                                            <div className="flex w-full flex-col gap-6 p-8">
                                                <div className="flex flex-col gap-2">
                                                    <div className="flex gap-4">
                                                        <p className="flex-1 text-display-xs font-semibold text-white">{featuredPost.title || 'Untitled Post'}</p>
                                                        <ArrowUpRight className="size-6 shrink-0 text-fg-white" />
                                                    </div>
                                                    <p className="line-clamp-2 text-md text-white">{summary}</p>
                                                </div>
                                                <div className="flex gap-6">
                                                    <div className="flex flex-1 gap-8">
                                                        <div className="flex flex-col gap-2">
                                                            <p className="text-sm font-semibold text-white">Written by</p>
                                                            <div className="flex items-center gap-2">
                                                                <Avatar focusable size="md" src={authorAvatarUrl} alt={authorName} />
                                                                <p className="text-sm font-semibold text-white">{authorName}</p>
                                                            </div>
                                                        </div>
                                                        <div className="flex flex-col gap-2">
                                                            <p className="text-sm font-semibold text-white">Published on</p>
                                                            <div className="flex h-10 items-center">
                                                                <p className="text-md font-semibold text-white">{publishedAt}</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })()}
                            </a>
                        )}

                        {/* Featured Post - Mobile */}
                        {featuredPost && (
                            <div className="md:hidden">
                                <BlogCardVertical article={featuredPost} />
                            </div>
                        )}

                        {/* Sort Controls */}
                        <div className="flex flex-col items-end gap-8 md:flex-row">
                            <div className="relative w-full md:max-w-44">
                                <Select
                                    aria-label="Sort by"
                                    size="md"
                                    selectedKey={sortBy}
                                    onSelectionChange={(value: string | number | null) => setSortBy(value as string)}
                                    items={sortByOptions}
                                >
                                    {(item: { id: string; label: string }) => <SelectItem id={item.id}>{item.label}</SelectItem>}
                                </Select>
                            </div>
                        </div>

                        {/* Posts Grid */}
                        {paginatedNonFeaturedPosts.length > 0 && (
                            <ul className="grid grid-cols-1 gap-x-8 gap-y-12 md:grid-cols-2 md:gap-y-12 lg:grid-cols-3">
                                {paginatedNonFeaturedPosts.map((post) => (
                                    <li key={post.id} className={cx(!isDesktop && "nth-[n+7]:hidden")}>
                                        <BlogCardVertical article={post} />
                                    </li>
                                ))}
                            </ul>
                        )}

                        {/* Pagination */}
                        {totalPages > 1 && (
                            <PaginationPageDefault 
                                rounded 
                                page={currentPage}
                                total={totalPages}
                                onPageChange={setCurrentPage}
                            />
                        )}
                    </>
                ) : (
                    <div className="text-center py-12">
                        <p className="text-gray-500">No blog posts available</p>
                    </div>
                )}
            </div>
        </section>
    );
};
