import { MapPin, Phone, Mail, Clock } from "lucide-react";
import type { Metadata } from "next";
import { cookies } from "next/headers";

import SectionHeading from "@/components/SectionHeading";
import Image from "next/image";
import FadeIn from "@/components/animations/FadeIn";
import ContactForm from "@/components/ContactForm";
import { getServiceNamesServer } from "@/services/contacts";
import { getContactPageContent, getContactPageInfo, getContactPageSeo } from "@/services/pages/public/contact";
import { getPublicGeneralSettings } from "@/services/settings/public";

export const revalidate = 1800;

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

  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/contact",
      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 ContactPage = async () => {
  const cookieStore = await cookies();
  const locale = cookieStore.get("locale")?.value ?? "en";

  const [serviceOptions, content, contactInfo, generalSettings, seo] = await Promise.all([
    getServiceNamesServer(locale),
    getContactPageContent(),
    getContactPageInfo(),
    getPublicGeneralSettings(),
    getContactPageSeo(),
  ]);

  const hero = content?.hero;
  const offices = content?.offices ?? [];
  const businessHours = content?.business_hours ?? [];
  const officesSection = content?.offices_section;
  const phones = [
    generalSettings?.phone_primary ?? contactInfo?.phone_primary,
    generalSettings?.phone_secondary ?? contactInfo?.phone_secondary,
  ].filter(Boolean) as string[];
  const emails = [
    generalSettings?.email_general ?? contactInfo?.email_general,
    generalSettings?.email_support ?? contactInfo?.email_support,
  ].filter(Boolean) as string[];

  // Normalize schema JSON to string
  let schemaJson = "";
  if (seo?.schema_json) {
    if (typeof seo.schema_json === "string") {
      schemaJson = seo.schema_json;
    } else {
      schemaJson = JSON.stringify(seo.schema_json);
    }
  }

  return (
    <>
      {schemaJson && (
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: schemaJson }} />
      )}
      <div className="min-h-screen bg-background">

      {/* 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 contact office"} className="absolute inset-0 w-full h-full object-cover" />
        ) : (
          <Image src="/contact.jpeg" width={1920} height={1080} alt="Petro-Base contact office" className="absolute inset-0 w-full h-full object-cover" />
        )}
        <div className="absolute inset-0 bg-primary/80" />
        <FadeIn
          y={30}
          duration={0.7}
          className="relative z-10 text-center petro-container"
        >
          <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 ?? "Get in Touch"}</span>
            <div className="w-12 h-[2px] bg-accent" />
          </div>
          <h1 className="text-4xl md:text-6xl font-bold text-primary-foreground mb-4 tracking-tight">
            {hero?.title ?? "Contact Us"}
          </h1>
          <p className="text-primary-foreground/70 max-w-2xl mx-auto text-lg">
            {hero?.description ?? "Ready to discuss your next project? Reach out to our team for engineering consultations, service inquiries, or partnership opportunities."}
          </p>
        </FadeIn>
      </section>

      {/* Contact Form + Info */}
      <section className="petro-section">
        <div className="petro-container">
          <div className="grid lg:grid-cols-5 gap-12">
            {/* Form */}
            <FadeIn
            direction="left"
            x={20}
            duration={0.5}
              className="lg:col-span-3"
            >
              <ContactForm serviceOptions={serviceOptions} />
            </FadeIn>

            {/* Sidebar Info */}
            <FadeIn
              direction="right"
              x={20}
                duration={0.5}
                delay={0.2}
              className="lg:col-span-2 space-y-8"
            >
              {/* Business Hours */}
              <div className="petro-card p-7">
                <h3 className="font-bold text-foreground mb-5 flex items-center gap-2">
                  <Clock size={20} className="text-accent" /> Business Hours
                </h3>
                <ul className="space-y-3">
                  {businessHours.map((bh) => (
                    <li key={bh.day} className="flex justify-between text-sm">
                      <span className="font-medium text-foreground">{bh.day}</span>
                      <span className={bh.hours === "Closed" ? "text-destructive font-semibold" : bh.day === "Emergency Support" ? "text-accent font-semibold" : "text-muted-foreground"}>
                        {bh.hours}
                      </span>
                    </li>
                  ))}
                </ul>
              </div>

              {/* Quick Contact */}
              <div className="petro-card p-7">
                <h3 className="font-bold text-foreground mb-5">Quick Contact</h3>
                <ul className="space-y-4 text-sm">
                  {phones.length > 0 && (
                    <li className="flex gap-3">
                      <Phone size={18} className="text-accent shrink-0 mt-0.5" />
                      <div>
                        <p className="font-semibold text-foreground">General Inquiries</p>
                        {phones.map((ph) => (
                          <div className="text-muted-foreground" key={ph}>
                            <a href={`tel:${ph}`} className="text-muted-foreground hover:text-accent transition-colors">{ph}</a>
                          </div>
                        ))}
                      </div>
                    </li>
                  )}
                  {emails.length > 0 && (
                    <li className="flex gap-3">
                      <Mail size={18} className="text-accent shrink-0 mt-0.5" />
                      <div>
                        <p className="font-semibold text-foreground">Email</p>
                        {emails.map((em) => (
                          <div className="text-muted-foreground" key={em}>
                            <a href={`mailto:${em}`} className="text-muted-foreground hover:text-accent transition-colors">{em}</a>
                          </div>
                        ))}
                      </div>
                    </li>
                  )}
                </ul>
              </div>
            </FadeIn>
          </div>
        </div>
      </section>

      {/* Office Locations */}
      <section className="petro-section bg-secondary">
        <div className="petro-container">
          <SectionHeading title={officesSection?.title ?? "Our Offices"} subtitle={officesSection?.subtitle ?? "Strategically located across Nigeria's key energy corridors."} />
          <div className="grid md:grid-cols-2 gap-6">
            {offices.map((office, i) => (
              <FadeIn
                key={office.city}
                delay={i * 0.1}
                duration={0.5}
                className="petro-card p-8"
              >
                <div className="flex items-center gap-3 mb-5">
                  <div className="p-3 bg-primary rounded-sm">
                    <MapPin className="text-accent" size={20} />
                  </div>
                  <div>
                    <h3 className="font-bold text-foreground">{office.city}</h3>
                    <span className="text-xs text-accent font-semibold uppercase tracking-wider">{office.role}</span>
                  </div>
                </div>
                <p className="text-sm font-medium text-foreground mb-3">{office.company}</p>
                <ul className="space-y-3 text-sm text-muted-foreground">
                  <li>{office.address}</li>
                  {office.phones.map((ph) => (
                    <li key={ph} className="flex gap-2 items-center"><Phone size={14} className="text-accent" /> {ph}</li>
                  ))}
                  {office.emails.map((em) => (
                    <li key={em} className="flex gap-2 items-center"><Mail size={14} className="text-accent" /> {em}</li>
                  ))}
                </ul>
              </FadeIn>
            ))}
          </div>
        </div>
      </section>

      </div>
    </>
  );
};

export default ContactPage;
