import { ChevronRight } from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import type { Metadata } from "next";
import FadeIn from "@/components/animations/FadeIn";
import CallToAction from "@/components/CallToAction";
import SectionHeading from "@/components/SectionHeading";
import { SECTOR_ICONS } from "@/lib/sectorIconMap";
import { Wrench } from "lucide-react";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
  PaginationEllipsis,
} from "@/components/ui/pagination";
import {
  getServicesPageContent,
  getServicesPageServices,
  getServicesPageSeo,
  type ServicesPageService,
} from "@/services/pages/public/services";

export const revalidate = 1800;

export async function generateMetadata(): Promise<Metadata> {
  const seo = await getServicesPageSeo();

  if (!seo) {
    return {
      title: "Services | Petro-Base Group",
      description: "Comprehensive engineering, inspection, and technical services",
    };
  }

  return {
    title: seo.meta_title,
    description: seo.meta_description,
    robots: seo.no_index ? "noindex, nofollow" : "index, follow",
    alternates: seo.canonical_url ? { canonical: seo.canonical_url } : {},
    openGraph: {
      title: seo.og_title,
      description: seo.og_description,
      url: "https://petrobasegroup.com/services",
      siteName: "Petro-Base Group",
      images: seo.og_image_url
        ? [
            {
              url: seo.og_image_url,
              width: 1200,
              height: 630,
              alt: seo.og_title,
            },
          ]
        : [],
      type: "website",
    },
  };
}

const ServicesPage = async ({
  searchParams,
}: {
  searchParams: Promise<{ page?: string }>;
}) => {
  const { page: pageParam } = await searchParams;
  const currentPage = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);

  const [content, { data: apiServices, meta }, seo] = await Promise.all([
    getServicesPageContent(),
    getServicesPageServices(currentPage),
    getServicesPageSeo(),
  ]);

  const lastPage = meta?.last_page ?? 1;

  const hero = content?.hero ?? {};
  const sectionHeading = content?.section_heading;
  const sectionSubtitle = content?.section_subtitle;

  const schemaJson = seo?.schema_json
    ? typeof seo.schema_json === "object"
      ? JSON.stringify(seo.schema_json)
      : seo.schema_json
    : null;

  return (
    <>
      {schemaJson && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: schemaJson }}
        />
      )}
      <div className="bg-background text-foreground">
      {/* Hero */}
      <section className="relative h-[50vh] min-h-[400px] flex items-center justify-center overflow-hidden">
        {hero.image_url ? (
          <Image
            src={hero.image_url}
            width={1920}
            height={1080}
            alt={hero.image_alt ?? "Petro-Base engineering services"}
            className="absolute inset-0 w-full h-full object-cover"
            priority
          />
        ) : (
          <Image
            src="/services-hero.jpg"
            width={1920}
            height={1080}
            alt="Petro-Base engineering services"
            className="absolute inset-0 w-full h-full object-cover"
            priority
          />
        )}
        <div className="absolute inset-0 bg-primary/80" />
        <div className="relative z-10 text-center petro-container">
          <FadeIn>
            <div className="flex items-center justify-center gap-4 mb-6">
              <div className="w-12 h-[2px] bg-accent" />
              <span className="petro-section-label-light">
                {hero.label ?? "Petro-Base Group"}
              </span>
              <div className="w-12 h-[2px] bg-accent" />
            </div>
            <h1 className="text-4xl md:text-6xl font-bold text-primary-foreground mb-6 tracking-tight">
              {hero.title ?? "Our Services"}
            </h1>
            <p className="text-primary-foreground/70 max-w-2xl mx-auto text-lg">
              {hero.description ??
                "Comprehensive engineering, inspection, and technical solutions across the entire energy lifecycle."}
            </p>
          </FadeIn>
        </div>
      </section>

      {/* Services Grid */}
      <section className="petro-section bg-secondary">
        <div className="petro-container">
          <SectionHeading title={sectionHeading} subtitle={sectionSubtitle} />
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
            {apiServices.map((svc: ServicesPageService, i: number) => {
                  const Icon =
                    (svc.icon ? SECTOR_ICONS[svc.icon]?.component : null) ??
                    Wrench;
                  const title =
                    svc.title ??
                    svc.slug
                      .replace(/-/g, " ")
                      .replace(/\b\w/g, (c) => c.toUpperCase());
                  return (
                    <FadeIn
                      key={svc.slug}
                      delay={i * 0.08}
                      whileHover={{ y: -5 }}
                      className="petro-card overflow-hidden group"
                    >
                      <div className="relative h-48 overflow-hidden">
                        {svc.image_url ? (
                          <Image
                            src={svc.image_url}
                            alt={title}
                            width={600}
                            height={400}
                            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                            loading="lazy"
                          />
                        ) : (
                          <div className="w-full h-full bg-primary/20" />
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-primary/80 to-transparent" />
                        <div className="absolute bottom-4 left-4 p-2.5 bg-primary-foreground/10 backdrop-blur-sm rounded-sm">
                          <Icon size={22} className="text-accent" />
                        </div>
                      </div>
                      <div className="p-6">
                        <h3 className="text-lg font-bold text-foreground mb-2 group-hover:text-primary transition-colors leading-tight">
                          {title}
                        </h3>
                        <p className="text-muted-foreground text-sm leading-relaxed mb-5">
                          {svc.short_desc}
                        </p>
                        <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-widest">
                          <span className="text-muted-foreground">
                            {svc.sub_services_count} service areas
                          </span>
                          <span className="text-border">•</span>
                          <span className="text-muted-foreground">
                            {svc.items_count} capabilities
                          </span>
                        </div>
                        <Link
                          href={`/services/${svc.slug}`}
                          className="petro-btn-gold text-[11px] mt-5 inline-flex items-center gap-2 w-full justify-center"
                        >
                          Explore Service <ChevronRight size={14} />
                        </Link>
                      </div>
                    </FadeIn>
                  );
                })}
          </div>
          {lastPage > 1 && (
            <div className="mt-12 flex justify-center">
              <Pagination>
                <PaginationContent>
                  {currentPage > 1 && (
                    <PaginationItem>
                      <PaginationPrevious href={`/services?page=${currentPage - 1}`} />
                    </PaginationItem>
                  )}

                  {Array.from({ length: lastPage }, (_, i) => i + 1).map((p) => {
                    const showPage =
                      p === 1 ||
                      p === lastPage ||
                      Math.abs(p - currentPage) <= 1;
                    const showEllipsisBefore =
                      p === currentPage - 2 && currentPage > 3;
                    const showEllipsisAfter =
                      p === currentPage + 2 && currentPage < lastPage - 2;

                    if (showEllipsisBefore) {
                      return (
                        <PaginationItem key={`ellipsis-before-${p}`}>
                          <PaginationEllipsis />
                        </PaginationItem>
                      );
                    }
                    if (showEllipsisAfter) {
                      return (
                        <PaginationItem key={`ellipsis-after-${p}`}>
                          <PaginationEllipsis />
                        </PaginationItem>
                      );
                    }
                    if (!showPage) return null;

                    return (
                      <PaginationItem key={p}>
                        <PaginationLink
                          href={`/services?page=${p}`}
                          isActive={p === currentPage}
                        >
                          {p}
                        </PaginationLink>
                      </PaginationItem>
                    );
                  })}

                  {currentPage < lastPage && (
                    <PaginationItem>
                      <PaginationNext href={`/services?page=${currentPage + 1}`} />
                    </PaginationItem>
                  )}
                </PaginationContent>
              </Pagination>
            </div>
          )}
        </div>
      </section>

      <CallToAction />
      </div>
    </>
  );
};

export default ServicesPage;
