import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import AboutMapClient from "@/components/AboutMapClient";
import {
  Globe, Target, Eye,
  ChevronRight, MapPin, ArrowLeft, CheckCircle2
} from "lucide-react";

import SectionHeading from "@/components/SectionHeading";
import FadeIn from "@/components/animations/FadeIn";
import AboutImageSlider from "@/components/AboutImageSlider";
import OurHistory from "@/components/OurHistory";
import { SECTOR_ICONS } from "@/lib/sectorIconMap";
import {
  getAboutPageContent,
  getAboutPageServices,
  getAboutPageHistory,
  getAboutPageStrengths,
  getAboutPageAffiliates,
  getAboutPageCoreValues,
  getAboutPageMapLocations,
  getAboutPageRegions,
  getAboutPageSeo,
  type AboutPageService,
} from "@/services/pages/public/about";

function renderBodyParagraph(text: string, className: string, services: AboutPageService[]) {
  if (!text.includes("{services}")) {
    return <p className={className}>{text}</p>;
  }
  const [before, after] = text.split("{services}");
  return (
    <p className={className}>
      {before}
      {services.map((s, i) => (
        <span key={s.slug}>
          <Link
            href={`/services/${s.slug}`}
            className="font-semibold text-accent hover:underline transition-colors"
          >
            {s.title}
          </Link>
          {i < services.length - 1 ? ", " : ""}
        </span>
      ))}
      {after}
    </p>
  );
}

export const revalidate = 1800;

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

  return {
    ...(seo?.meta_title ? { title: seo.meta_title } : {}),
    ...(seo?.meta_description ? { description: seo.meta_description } : {}),
    ...(seo?.no_index ? { robots: { index: false, follow: false } } : {}),
    ...(seo?.canonical_url ? { alternates: { canonical: seo.canonical_url } } : {}),
    openGraph: {
      ...(seo?.og_title ? { title: seo.og_title } : {}),
      ...(seo?.og_description ? { description: seo.og_description } : {}),
      ...(seo?.og_image_url ? { images: [{ url: seo.og_image_url }] } : {}),
    },
  };
}

const AboutPage = async () => {
  const [
    coreValues,
    affiliates,
    strengths,
    regions,
    mapLocationsRes,
    pageContent,
    historyMilestonesRes,
    aboutServices,
    seo,
  ] = await Promise.all([
    getAboutPageCoreValues(),
    getAboutPageAffiliates(),
    getAboutPageStrengths(),
    getAboutPageRegions(),
    getAboutPageMapLocations(),
    getAboutPageContent(),
    getAboutPageHistory(),
    getAboutPageServices(),
    getAboutPageSeo(),
  ]);

  const mapLocations = mapLocationsRes.map((l) => ({ name: l.name, lat: Number(l.lat), lng: Number(l.lng) }));
  const historyMilestones = historyMilestonesRes.map((m) => ({ ...m, year: String(m.year) }));

  const hero = pageContent?.hero;
  const aboutData = pageContent?.about;
  const sectionHeadings = pageContent?.section_headings;
  const badge = pageContent?.badge;
  const stats = pageContent?.stats ?? [];

  const visionText = pageContent?.about_vision;
  const missionText = pageContent?.about_mission;

  const historyHeading = sectionHeadings?.history?.heading;
  const historySubtitle = sectionHeadings?.history?.subtitle;
  const strengthsHeading = sectionHeadings?.strengths?.heading;
  const strengthsSubtitle = sectionHeadings?.strengths?.subtitle;
  const affiliatesHeading = sectionHeadings?.affiliates?.heading;
  const affiliatesSubtitle = sectionHeadings?.affiliates?.subtitle;
  const mvvHeading = sectionHeadings?.mvv?.heading;
  const coreValuesHeading = sectionHeadings?.core_values?.heading;
  const globalPresenceHeading = sectionHeadings?.global_presence?.heading;
  const globalPresenceSubtitle = sectionHeadings?.global_presence?.subtitle;

  const aboutBody1 = aboutData?.body_1;
  const aboutBody2 = aboutData?.body_2;

  const aboutImages = aboutData?.images?.map((img) => ({ src: img.url, alt: img.alt }));
  const yearsBadgeValue = badge?.value;
  const yearsBadgeLabel = badge?.label;

  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 Banner */}
      <section className="relative h-[60vh] min-h-[400px] flex items-center justify-center overflow-hidden">
        {hero?.image_url ? (
          <Image src={hero.image_url} width={1920} height={1080} priority alt={hero.image_alt ?? "Petro-Base About"} className="absolute inset-0 w-full h-full object-cover" />
        ) : null}
        <div className="absolute inset-0 bg-primary/80" />
        <FadeIn y={30} className="relative z-10 text-center px-6">
          {hero?.label && (
            <div className="flex items-center justify-center gap-3 mb-6">
              <div className="w-12 h-[2px] bg-accent" />
              <span className="petro-section-label-light">{hero.label}</span>
              <div className="w-12 h-[2px] bg-accent" />
            </div>
          )}
          {hero?.title && (
            <h1 className="text-4xl md:text-6xl font-bold text-primary-foreground mb-4 tracking-tight">
              {hero.title}
            </h1>
          )}
          {hero?.description && (
            <p className="text-primary-foreground/70 text-lg md:text-xl max-w-2xl mx-auto">
              {hero.description}
            </p>
          )}
        </FadeIn>
      </section>

      {/* Who We Are */}
      <section className="petro-section">
        <div className="petro-container">
          <div className="grid lg:grid-cols-2 gap-16 items-center">
            <FadeIn direction="left" x={30}
            >
              <SectionHeading title={aboutData?.heading} />
              {aboutBody1 && renderBodyParagraph(aboutBody1, "text-muted-foreground leading-relaxed mb-6 text-justify", aboutServices)}
              {aboutBody2 && renderBodyParagraph(aboutBody2, "text-muted-foreground leading-relaxed mb-8 text-justify", aboutServices)}
              <div className="grid grid-cols-2 gap-6">
                {stats.map((stat, i) => (
                  <FadeIn
                    key={i}
                    delay={i * 0.15}
                    className="text-center p-4 bg-secondary rounded-sm"
                  >
                    <div className="text-2xl font-bold text-accent">{stat.value}</div>
                    <div className="text-xs uppercase tracking-widest text-muted-foreground mt-1">{stat.label}</div>
                  </FadeIn>
                ))}
              </div>
            </FadeIn>

            <FadeIn
              direction="right"
              x={30}
              className="relative"
            >
              <AboutImageSlider images={aboutImages} badgeValue={yearsBadgeValue} badgeLabel={yearsBadgeLabel} />
            </FadeIn>
          </div>
        </div>
      </section>

      {/* Our History */}
      <OurHistory milestones={historyMilestones} heading={historyHeading} subtitle={historySubtitle} />

      {/* Strengths */}
      <section className="bg-secondary petro-section">
        <div className="petro-container">
          <SectionHeading title={strengthsHeading} subtitle={strengthsSubtitle} />
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {strengths.map((s, i) => {
              const IconComp = SECTOR_ICONS[s.icon]?.component ?? SECTOR_ICONS["Zap"].component;
              return (
                <FadeIn
                  key={i}
                  delay={i * 0.1}
                  className="petro-card p-6 flex items-start gap-4"
                >
                  <div className="w-12 h-12 bg-accent/10 flex items-center justify-center shrink-0">
                    <IconComp className="text-accent" size={22} />
                  </div>
                  <p className="font-semibold text-foreground">{s.text}</p>
                </FadeIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* Affiliates */}
      <section className="petro-section">
        <div className="petro-container">
          <SectionHeading title={affiliatesHeading} subtitle={affiliatesSubtitle} />
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {affiliates.map((a, i) => (
              <FadeIn
                key={i}
                delay={i * 0.1}
                className="petro-card p-6 border-t-4 border-t-accent"
              >
                <div className="flex items-center gap-3 mb-4">
                  <MapPin className="text-accent shrink-0" size={18} />
                  <span className="text-xs uppercase tracking-widest font-bold text-accent">{a.country}</span>
                </div>
                <h3 className="font-bold text-foreground text-sm mb-3">{a.entity}</h3>
                {a.sub_entity && (
                  <p className="text-xs text-muted-foreground mb-2">{a.sub_entity}</p>
                )}
                {a.subs && (
                  <ul className="space-y-1.5">
                    {a.subs.map((sub, j) => (
                      <li key={j} className="text-xs text-muted-foreground flex items-start gap-2">
                        <ChevronRight size={12} className="text-accent mt-0.5 shrink-0" />
                        {sub}
                      </li>
                    ))}
                  </ul>
                )}
              </FadeIn>
            ))}
          </div>
        </div>
      </section>

      {/* Mission, Vision, Values */}
      <section className="bg-primary petro-section">
        <div className="petro-container">
          <SectionHeading title={mvvHeading} light />

          <div className="grid md:grid-cols-2 gap-8 mb-16">
            {/* Vision */}
            <FadeIn
              className="bg-primary-foreground/5 backdrop-blur-sm border border-primary-foreground/10 p-8 rounded-sm"
            >
              <div className="flex items-center gap-3 mb-4">
                <Eye className="text-accent" size={28} />
                <h3 className="text-xl font-bold text-primary-foreground">Our Vision</h3>
              </div>
              <p className="text-primary-foreground/70 leading-relaxed">
                {visionText}
              </p>
            </FadeIn>

            {/* Mission */}
            <FadeIn
              delay={0.1}
              className="bg-primary-foreground/5 backdrop-blur-sm border border-primary-foreground/10 p-8 rounded-sm"
            >
              <div className="flex items-center gap-3 mb-4">
                <Target className="text-accent" size={28} />
                <h3 className="text-xl font-bold text-primary-foreground">Our Mission</h3>
              </div>
              <p className="text-primary-foreground/70 leading-relaxed">
                {missionText}
              </p>
            </FadeIn>
          </div>

          {/* Core Values */}
          <h3 className="text-xl font-bold text-primary-foreground mb-8">{coreValuesHeading}</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {coreValues.map((v, i) => {
              const IconComp = SECTOR_ICONS[v.icon]?.component ?? SECTOR_ICONS["Shield"].component;
              return (
                <FadeIn
                  key={i}
                  delay={i * 0.06}
                  className="bg-primary-foreground/5 border border-primary-foreground/10 p-5 text-center rounded-sm hover:bg-primary-foreground/10 transition-colors"
                >
                  <IconComp className="text-accent mx-auto mb-3" size={24} />
                  <h4 className="font-bold text-primary-foreground text-sm mb-1">{v.title}</h4>
                  <p className="text-primary-foreground/50 text-xs">{v.desc}</p>
                </FadeIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* Global Presence */}
      <section className="petro-section">
        <div className="petro-container">
          <SectionHeading title={globalPresenceHeading} subtitle={globalPresenceSubtitle} />

          {/* Interactive Map */}
          <AboutMapClient locations={mapLocations} />

          {/* Regions Grid */}
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
            {regions.map((region, i) => (
              <FadeIn
                key={i}
                delay={i * 0.1}
                className="petro-card p-6"
              >
                <div className="flex items-center gap-2 mb-4">
                  <Globe className="text-accent" size={18} />
                  <h4 className="font-bold text-foreground text-sm">{region.name}</h4>
                </div>
                <ul className="space-y-2">
                  {region.countries.map((c, j) => (
                    <li key={j} className="flex items-center gap-2 text-sm text-muted-foreground">
                      <CheckCircle2 size={12} className="text-accent shrink-0" />
                      {c}
                    </li>
                  ))}
                </ul>
              </FadeIn>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="bg-primary py-20 px-6">
        <div className="petro-container text-center">
          <FadeIn
            delay={0.1}
          >
            <h2 className="text-3xl md:text-4xl font-bold text-primary-foreground mb-4">
              Ready to Partner with Us?
            </h2>
            <p className="text-primary-foreground/60 mb-8 max-w-xl mx-auto">
              Let's discuss how Petro-Base Group can support your next project with world-class engineering services.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <a href="/#contact" className="petro-btn-gold">Request a Quote</a>
              <Link href="/" className="petro-btn-outline flex items-center gap-2 justify-center">
                <ArrowLeft size={16} /> Back to Home
              </Link>
            </div>
          </FadeIn>
        </div>
      </section>

    </div>
    </>
  );
};

export default AboutPage;
