import { GET } from "@/utils/get";
import { Offer } from "@/types/models";
import { OfferCard } from "./_components/offer-card";
import { getTranslations } from "next-intl/server";
import { Badge } from "@/components/ui/badge";
import { Percent, Tag, Zap } from "lucide-react";
import { Metadata } from "next";

export const generateMetadata = async ({ params }: { params: Promise<{ locale: string }> }): Promise<Metadata> => {
    const { locale } = await params;
    const t = await getTranslations({ locale });

    const pageTitle = locale === 'ar'
        ? "أقوى عروض الدورات والبرامج التدريبية المعتمدة | مواهب"
        : "Best Exclusive Training Courses & Program Offers | Mwaheb";

    const pageDescription = locale === 'ar'
        ? "استفد من أقوى العروض الحصرية والخصومات المميزة على الدورات التدريبية المعتمدة في مركز مواهب. طوّر مهاراتك المهنية والعملية اليوم ووفر الكثير مع شهادات معتمدة."
        : "Discover exclusive training offers and discount deals on certified professional courses at Mwaheb. Upgrade your career skills today with official certificates.";

    // Generate exact 100 character keywords dynamically
    const baseKeywords = locale === 'ar'
        ? ["عروض دورات", "خصومات تدريب", "أقوى العروض", "دورات معتمدة", "تخفيضات مواهب"]
        : ["training offers", "course discounts", "certified courses", "mwaheb deals", "exclusive offers"];

    const finalKeywords = [...baseKeywords];
    const currentString = finalKeywords.join(',');
    if (currentString.length < 100) {
        const diff = 100 - currentString.length;
        if (diff >= 3) {
            const padSource = locale === 'ar'
                ? "منصة مواهب للتعليم والتدريب المعتمد تطوير مهارات احترافية مهنية شهادة"
                : "mwaheb certified education training platform professional career skills development certificate";
            const neededLength = diff - 1;
            const padKeyword = padSource.substring(0, neededLength);
            finalKeywords.push(padKeyword);
        } else if (diff > 0) {
            const lastIdx = finalKeywords.length - 1;
            if (lastIdx >= 0) {
                finalKeywords[lastIdx] = finalKeywords[lastIdx].padEnd(finalKeywords[lastIdx].length + diff, '.');
            }
        }
    }

    // Final safety checks
    const finalString = finalKeywords.join(',');
    if (finalString.length > 100) {
        const diff = finalString.length - 100;
        const lastIdx = finalKeywords.length - 1;
        if (lastIdx >= 0) {
            finalKeywords[lastIdx] = finalKeywords[lastIdx].substring(0, finalKeywords[lastIdx].length - diff);
        }
    }

    const canonicalUrl = `https://next.ivorytraining.com/${locale}/programs/offers`;

    return {
        title: {
            absolute: pageTitle
        },
        description: pageDescription,
        keywords: finalKeywords,
        alternates: {
            canonical: canonicalUrl,
            languages: {
                'ar': 'https://next.ivorytraining.com/ar/programs/offers',
                'en': 'https://next.ivorytraining.com/en/programs/offers',
                'x-default': 'https://next.ivorytraining.com/ar/programs/offers'
            }
        },
        openGraph: {
            title: pageTitle,
            description: pageDescription,
            url: canonicalUrl,
            siteName: `${pageTitle} | ${t("mwaheb")}`,
            images: [{
                url: "https://tr.ivorytraining.com/images/logo.png"
            }],
            type: "website"
        },
        twitter: {
            card: "summary_large_image",
            title: pageTitle,
            description: pageDescription,
            images: ["https://tr.ivorytraining.com/images/logo.png"]
        }
    };
};

async function getOffers() {
    try {
        const response = await GET({ url: "/offers", revalidate: 0 });
        return response?.offers?.data || [];
    } catch (error) {
        console.error("Failed to fetch offers:", error);
        return [];
    }
}

export default async function OffersPage({ params }: { params: Promise<{ locale: string }> }) {
    const { locale } = await params;
    const offers: Offer[] = await getOffers();
    const t = await getTranslations();

    const hasAnyOffer = offers.length > 0;

    return (
        <main className="py-20 bg-gray-50/50 min-h-screen">
            <div className="box mx-auto px-4 sm:px-6 lg:px-8">
                {/* Header Section */}
                <div className="relative mb-24 text-center">
                    <div className="absolute inset-0 flex items-center justify-center opacity-5 blur-[120px] pointer-events-none">
                        <div className="size-96 bg-primary-tw-600 rounded-full" />
                    </div>
                    
                    <div className="relative z-10 space-y-6">
                        <Badge className="bg-red-50 text-red-600 border-red-100 hover:bg-red-50 px-6 py-1.5 animate-pulse uppercase tracking-[0.2em] font-black text-[10px] rounded-full shadow-sm">
                           <Zap className="size-3 mr-2 inline" /> {t("custom.limited-time") || "LIMITED TIME OFFER"} <Zap className="size-3 ml-2 inline" />
                        </Badge>
                        <h1 className="text-5xl md:text-7xl font-black text-gray-900 tracking-tight leading-tight">
                            {t("custom.exclusive_offers") || "Exclusive Training Offers"}
                        </h1>
                        <p className="max-w-3xl mx-auto text-gray-500 font-medium text-lg md:text-xl leading-relaxed">
                            {t("custom.offers_desc") || "Invest in your future with our premium training programs at unbeatable prices. Seize the opportunity to excel today."}
                        </p>
                    </div>

                    <div className="flex items-center justify-center gap-12 mt-12">
                        <div className="flex flex-col items-center gap-2 group">
                            <div className="size-14 rounded-2xl bg-white shadow-xl flex items-center justify-center text-primary-tw-600 group-hover:scale-110 transition-all duration-300 border border-gray-50">
                                <Tag className="size-7" />
                            </div>
                            <span className="text-[10px] font-black uppercase tracking-widest text-gray-400 group-hover:text-primary-tw-600 transition-colors">
                                {t("custom.elite_quality") || "Elite Quality"}
                            </span>
                        </div>
                        <div className="h-10 w-px bg-gradient-to-b from-transparent via-gray-200 to-transparent" />
                        <div className="flex flex-col items-center gap-2 group">
                            <div className="size-14 rounded-2xl bg-white shadow-xl flex items-center justify-center text-red-600 group-hover:scale-110 transition-all duration-300 border border-gray-50">
                                <Percent className="size-7" />
                            </div>
                            <span className="text-[10px] font-black uppercase tracking-widest text-gray-400 group-hover:text-red-600 transition-colors">
                                {t("custom.hot_deals") || "Hot Deals"}
                            </span>
                        </div>
                    </div>
                </div>

                {hasAnyOffer ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
                        {offers.map((offer) => (
                            <OfferCard key={offer.id} offer={offer} />
                        ))}
                    </div>
                ) : (
                    <div className="text-center py-20 bg-white rounded-3xl shadow-xl border border-dashed border-gray-200 max-w-2xl mx-auto">
                        <div className="size-24 bg-gray-50 rounded-2xl flex items-center justify-center mx-auto mb-6 transform -rotate-12">
                            <Tag className="size-12 text-gray-300" />
                        </div>
                        <h3 className="text-2xl font-black text-gray-900 mb-3">{t("custom.no_offers") || "Checking for new offers..."}</h3>
                        <p className="text-gray-500 px-10">{t("custom.no_offers_desc") || "We are currently curating new exclusive deals for you. Please check back shortly for limited-time opportunities."}</p>
                    </div>
                )}
            </div>
        </main>
    );
}
