import { GET } from "@/utils/get";
import { Program } from "@/types/models";
import { getTranslations } from "next-intl/server";
import { ProgramBox } from "./_components/program-box";

export const generateMetadata = async () => {
    const t = await getTranslations();
    return {
        title: `${t('routes.programs')}` || "Mwaheb"
    }
};

export default async function Programs({ searchParams }) {
    const t = await getTranslations();
    const params = await searchParams
    const programs = await GET({ url: "/user/groups/records", searchParams: params, context: "dashboard" });

    // Sort programs: items with 100% progress should be moved to the end
    const sortedPrograms = programs ? [...programs].sort((a: Program, b: Program) => {
        const aProgress = a.progress_percentage || 0;
        const bProgress = b.progress_percentage || 0;
        
        if (aProgress === 100 && bProgress !== 100) return 1;
        if (aProgress !== 100 && bProgress === 100) return -1;
        return 0;
    }) : [];

    return (
        <main className="p-4 bg-white space-y-8">
            <h1 className="text-2xl font-bold">
                {t("routes.programs")}
            </h1>

            <section className="grid md:grid-cols-3 gap-4">
                {
                    sortedPrograms.length > 0 ?
                        sortedPrograms.map((program: Program, index: number) => (
                            <ProgramBox key={index} program={program} />
                        ))
                        :
                        <div className="grid place-items-center min-h-[50dvh] md:col-span-3 font-semibold">
                            {t('custom.no results')}
                        </div>
                }
            </section>

        </main>
    );
};