import { notFound, redirect } from 'next/navigation';
import { Container, Badge, Heading } from '@/components/ui';
import { getTranslations, setRequestLocale } from 'next-intl/server';
import { Metadata } from 'next';
import { getPageBySlug } from '@/lib/pages';
import { mapSlugToFileSlug, mapFileSlugToTranslated } from '@/lib/slugs';
import { MDXRemote } from 'next-mdx-remote/rsc';
import { SITE_URL } from '@/lib/schema';
import TrackedLink from '@/components/analytics/TrackedLink';
import { getButtonClasses, ButtonOverlay } from '@/components/ui/Button';

// Import components used in MDX
import { HeroVideo as HomeHero } from '@/components/blocks/HeroVideo';
import { SubCompanyTiles as HomeSubCompanyTiles } from '@/components/blocks/SubCompanyTiles';
import { CompetenceBentoGrid as HomeCompetenceBentoGrid } from '@/components/blocks/CompetenceBentoGrid';
import { ReferencesSlider as HomeReferencesSlider } from '@/components/blocks/ReferencesSlider';
import { CompanyTimeline } from '@/components/blocks/CompanyTimeline';
import { JobListingBlock } from '@/components/blocks/JobListingBlock';
import { CallToAction } from '@/components/blocks/CallToAction';

const mdxComponents = {
  HomeHero,
  HomeSubCompanyTiles,
  HomeCompetenceBentoGrid,
  HomeReferencesSlider,
  CompanyTimeline,
  JobListingBlock,
  CallToAction,
};

interface PageProps {
  params: Promise<{
    locale: string;
    slug: string;
  }>;
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { locale, slug } = await params;
  
  // Guard against invalid locales
  if (locale !== 'de' && locale !== 'en') return {};

  const pageData = await getPageBySlug(slug, locale);

  if (!pageData) return {};

  const fileSlug = await mapSlugToFileSlug(pageData.slug || slug, locale);
  const deSlug = await mapFileSlugToTranslated(fileSlug, 'de');
  const enSlug = await mapFileSlugToTranslated(fileSlug, 'en');

  // Determine correct localized slug based on current locale
  const currentLocaleSlug = locale === 'de' ? deSlug : enSlug;

  return {
    title: pageData.frontmatter.title,
    description: pageData.frontmatter.excerpt || '',
    alternates: {
      canonical: `${SITE_URL}/${locale}/${currentLocaleSlug}`,
      languages: {
        de: `${SITE_URL}/de/${deSlug}`,
        en: `${SITE_URL}/en/${enSlug}`,
        'x-default': `${SITE_URL}/en/${enSlug}`,
      },
    },
    openGraph: {
      title: `${pageData.frontmatter.title} | E-TIB`,
      description: pageData.frontmatter.excerpt || '',
      url: `${SITE_URL}/${locale}/${currentLocaleSlug}`,
    },
    twitter: {
      card: 'summary_large_image',
      title: `${pageData.frontmatter.title} | E-TIB`,
      description: pageData.frontmatter.excerpt || '',
    },
  };
}

export default async function Page(props: { params: Promise<{ locale: string; slug: string }> }) {
  const { locale, slug } = await props.params;
  
  // Guard against invalid locales (e.g. favicon.ico) hitting the DB
  if (locale !== 'de' && locale !== 'en') {
    notFound();
  }
  
  setRequestLocale(locale);
  const pageData = await getPageBySlug(slug, locale);
  const t = await getTranslations('StandardPage');

  if (!pageData) {
    notFound();
  }

  // Redirect logic removed to simplify for now, as slugs match file names
  /*
  const fileSlug = await mapSlugToFileSlug(pageData.slug || slug, locale);
  const correctSlug = await mapFileSlugToTranslated(fileSlug, locale);
  if (correctSlug && correctSlug !== slug) {
    redirect(`/${locale}/${correctSlug}`);
  }
  */

  // Full-bleed pages render blocks edge-to-edge without the generic article wrapper
  if (pageData.frontmatter.layout === 'fullBleed') {
    return (
      <div className="flex flex-col min-h-screen">
        <MDXRemote source={pageData.content} components={mdxComponents} />
      </div>
    );
  }

  // Default article layout with hero, content, and support CTA
  return (
    <div className="flex flex-col min-h-screen bg-white">
      {/* Hero Section */}
      <section className="bg-primary-dark text-white py-20 md:py-32 relative overflow-hidden">
        <div className="absolute inset-0 opacity-20">
          <div className="absolute top-0 left-0 w-full h-full bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-accent via-transparent to-transparent" />
        </div>
        <Container className="relative z-10">
          <div className="max-w-4xl">
            <Badge variant="accent" className="mb-4 md:mb-6">
              {t('badge')}
            </Badge>
            <Heading level={1} className="text-white mb-0">
              {pageData.frontmatter.title}
            </Heading>
          </div>
        </Container>
      </section>

      {/* Main Content Area */}
      <div className="container mx-auto px-4 py-16 md:py-24">
        <div className="max-w-4xl mx-auto">
          {/* Excerpt/Lead paragraph if available */}
          {pageData.frontmatter.excerpt && (
            <div className="mb-16">
              <p className="text-xl md:text-2xl text-text-primary leading-relaxed font-medium border-l-4 border-primary pl-8 py-2 italic">
                {pageData.frontmatter.excerpt}
              </p>
            </div>
          )}

          {/* Main content */}
          <div className="prose prose-lg md:prose-xl max-w-none prose-headings:font-bold prose-headings:text-text-primary prose-p:text-text-secondary prose-p:leading-relaxed prose-a:text-primary prose-a:no-underline hover:prose-a:underline prose-img:rounded-2xl prose-img:shadow-2xl prose-blockquote:border-primary prose-blockquote:bg-primary/5 prose-blockquote:rounded-r-2xl prose-strong:text-primary">
            <MDXRemote source={pageData.content} components={mdxComponents} />
          </div>

          {/* Support Section */}
          <div className="mt-24 p-8 md:p-12 bg-primary-dark rounded-3xl text-white shadow-2xl relative overflow-hidden group animate-slight-fade-in-from-bottom">
            <div className="absolute top-0 right-0 w-64 h-full bg-accent/5 -skew-x-12 translate-x-1/2 transition-transform group-hover:translate-x-1/3" />
            <div className="relative z-10 max-w-2xl">
              <h3 className="text-2xl md:text-3xl font-bold mb-4">{t('needHelp')}</h3>
              <p className="text-lg text-white/70 mb-8">{t('supportTeamAvailable')}</p>
              <TrackedLink
                href={`/${locale}/${locale === 'de' ? 'kontakt' : 'contact'}`}
                className={getButtonClasses('accent', 'lg')}
                eventProperties={{
                  location: 'generic_page_support_cta',
                  page_slug: slug,
                }}
              >
                <span className="relative z-10 flex items-center justify-center gap-2 transition-colors duration-500 group-hover/btn:text-primary-dark">
                  {t('contactUs')}
                  <span className="ml-2 transition-transform group-hover/btn:translate-x-1">
                    &rarr;
                  </span>
                </span>
                <ButtonOverlay variant="accent" />
              </TrackedLink>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
