import { formatDateToMonthDayYear } from "@/lib/utils";
import { Chapter, Ad } from "@/lib/types";
import { fetchReleases } from "@/lib/api";
import Link from "next/link";


export const metadata = {
    title: 'Release page',
    description: 'NullTranslationGroup Announcement page',
};

export default async function ReleasePage() {
    let current_chapters: Chapter[] = [];
    let future_chapters: Chapter[] = [];
    try {
        const releases = await fetchReleases();
        current_chapters = releases.current_chapters
        future_chapters = releases.future_chapters
    } catch (error) {
        console.error(error);
        return (
            <div className="text-center mt-10 text-red-500">
                <p>Failed to load releases.</p>
            </div>
        );
    }
    const sorted_current_chapters = current_chapters.sort((a, b) => new Date(a.release_datetime).getTime() - new Date(b.release_datetime).getTime());
    const sorted_future_chapters = future_chapters.sort((a, b) => new Date(a.release_datetime).getTime() - new Date(b.release_datetime).getTime());
    const groupChaptersByNovel = (chapters: Chapter[]) => {
        return chapters.reduce((acc, chapter) => {
            const bookTitle = chapter.book?.title || "Unknown Title";
            if (!acc[bookTitle]) {
                acc[bookTitle] = [];
            }
            acc[bookTitle].push(chapter);
            return acc;
        }, {} as Record<string, Chapter[]>);
    };

    const groupedCurrentChapters = groupChaptersByNovel(sorted_current_chapters)
    const groupedFutureChapters = groupChaptersByNovel(sorted_future_chapters);

    return (
        <div className="mx-auto p-6 bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-screen">
            <div className="hidden md:block bg-yellow-500 text-black py-2 px-4 rounded-lg hover:bg-yellow-600 transition duration-200 mb-6">
                    <a
                      href={Ad.patreon}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="font-semibold text-center block"
                    >
                        WANT TO READ AHEAD OF SCHEDULE ? JOIN OUR PATREON !
                    </a>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                {/* Current Releases Section */}
                <div>
                    <h2 className="text-2xl font-bold text-yellow-500 mb-6 border-b-2 border-yellow-500 pb-2">
                        Current Releases
                    </h2>
                    {Object.keys(groupedCurrentChapters).length > 0 ? (
                        Object.entries(groupedCurrentChapters)
                            .sort(([titleA], [titleB]) => titleA.localeCompare(titleB))
                            .map(([bookTitle, chapters]) => (
                                <div key={bookTitle} className="mb-6">
                                    <Link href={`/books/${chapters[0].book?.documentId}`}
                                        className="text-lg font-semibold text-gray-700 dark:text-yellow-300 mb-4 hover:underline">
                                        {bookTitle}
                                    </Link>
                                    <ul className="space-y-4">
                                        {chapters.map((chapter) => (
                                            <li
                                                key={chapter.id}
                                                className="p-4 bg-yellow-100 dark:bg-yellow-800 text-gray-800 dark:text-gray-100 rounded-lg shadow-sm border border-yellow-300 dark:border-yellow-700 transition-transform transform hover:scale-105"
                                            >
                                                <Link href={`books/${chapter.book?.documentId}/chapters/${chapter.documentId}`} className="block">

                                                    <h4 className="text-md font-medium">
                                                        Chapter {chapter.number}: {chapter.title}
                                                    </h4>
                                                    <p className="text-sm">
                                                        Released on:{" "}
                                                        {formatDateToMonthDayYear(
                                                            new Date(chapter.release_datetime)
                                                        )}
                                                    </p>
                                                </Link>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            ))
                    ) : (
                        <p className="text-gray-600 dark:text-gray-400 italic">
                            No current releases available.
                        </p>
                    )}
                </div>

                {/* Future Releases Section */}
                <div>
                    <h2 className="text-2xl font-bold text-blue-500 mb-6 border-b-2 border-blue-500 pb-2">
                        Future Releases
                    </h2>
                    {Object.keys(groupedFutureChapters).length > 0 ? (
                        Object.entries(groupedFutureChapters)
                            .sort(([titleA], [titleB]) => titleA.localeCompare(titleB))
                            .map(([bookTitle, chapters]) => (
                                <div key={bookTitle} className="mb-6">
                                    <Link href={`/books/${chapters[0].book?.documentId}`}
                                        className="text-lg font-semibold text-blue-700 dark:text-blue-300 mb-4 hover:underline">
                                        {bookTitle}
                                    </Link>
                                    <ul className="space-y-4">
                                        {chapters.map((chapter) => (
                                            <li
                                                key={chapter.id}
                                                className="p-4 bg-blue-100 dark:bg-blue-800 text-gray-800 dark:text-gray-100 rounded-lg shadow-sm border border-blue-300 dark:border-blue-700 transition-transform transform hover:scale-105"
                                            >
                                                <h4 className="text-md font-medium">
                                                    Chapter {chapter.number}: {chapter.title}
                                                </h4>
                                                <p className="text-sm">
                                                    Release date:{" "}
                                                    {formatDateToMonthDayYear(
                                                            new Date(chapter.release_datetime)
                                                    )}
                                                </p>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            ))
                    ) : (
                        <p className="text-gray-600 dark:text-gray-400 italic">
                            No future releases available.
                        </p>
                    )}
                </div>
            </div>
        </div>
    );

}
