import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowRight, ArrowUpRight, Check } from "lucide-react";
import {
  isLocale,
  isServiceSlug,
  localizedPath,
  locationSlugs,
  serviceSlugs,
  servicesWithLegalNotice,
  type Locale,
  type ServiceSlug,
} from "@alterra/shared";
import PageHero from "@/components/PageHero";
import ClosingCta from "@/components/ClosingCta";
import Reveal from "@/components/Reveal";
import RevealImage from "@/components/RevealImage";
import SectionHeading from "@/components/SectionHeading";
import FaqList from "@/components/services/FaqList";
import InvestorProfileForm from "@/components/services/InvestorProfileForm";
import PropertyCard from "@/components/properties/PropertyCard";
import { buildCrumbs } from "@/lib/breadcrumbs";
import { fetchProperties } from "@/lib/api";
import { images } from "@/lib/i18n";
import { getPropertyCopy } from "@/lib/propertyCopy";
import { getServiceContent, getServiceUi, type LocalizedService, type ServiceUi } from "@/lib/servicesContent";
import { getFormMessages, getLayoutCopy, legalNotice, locations, services } from "@/lib/site";
import { pageMetadata } from "@/lib/seo";

type Params = Promise<{ lang: string; slug: string }>;

export const dynamicParams = false;
export const revalidate = 60;
export const generateStaticParams = () => serviceSlugs.map((slug) => ({ slug }));

const resolve = async (params: Params) => {
  const { lang, slug } = await params;
  if (!isLocale(lang) || !isServiceSlug(slug)) return null;
  return { lang, slug };
};

export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
  const r = await resolve(params);
  if (!r) return {};
  const content = getServiceContent(r.slug, r.lang);
  return pageMetadata({ lang: r.lang, path: `/services/${r.slug}`, title: services[r.slug].name[r.lang], description: content.summary });
}

function Section({ children, tone = "cream" }: { children: React.ReactNode; tone?: "cream" | "sand" }) {
  return (
    <section className={tone === "cream" ? "bg-cream" : "bg-sand/60"}>
      <div className="mx-auto max-w-7xl px-5 py-20 md:px-8 md:py-28">{children}</div>
    </section>
  );
}

function Overview({ content, ui }: { content: LocalizedService; ui: ServiceUi }) {
  return (
    <Section>
      <div className="grid gap-14 lg:grid-cols-[1.1fr_1fr] lg:gap-20">
        <div>
          <Reveal>
            <p className="font-serif text-3xl leading-snug text-ink md:text-[2.4rem] md:leading-[1.25]">{content.summary}</p>
          </Reveal>
          <RevealImage src={content.image} alt="" sizes="(min-width: 1024px) 45vw, 100vw" className="mt-12 aspect-[16/10]" />
        </div>
        <div>
          <p className="eyebrow flex items-center gap-4 text-gold-ink">
            <span className="h-px w-10 bg-gold" aria-hidden />
            {ui.whatWeDo}
          </p>
          <ul className="mt-8 border-t border-ink/10">
            {content.whatWeDo.map((item, i) => (
              <li key={item} className="border-b border-ink/10">
                <Reveal delay={i * 0.05} className="flex items-start gap-4 py-5">
                  <Check size={17} strokeWidth={1.6} className="mt-1 shrink-0 text-gold-ink" />
                  <span className="text-lg">{item}</span>
                </Reveal>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </Section>
  );
}

function WhoFor({ content, ui }: { content: LocalizedService; ui: ServiceUi }) {
  return (
    <Section tone="sand">
      <SectionHeading eyebrow={ui.whoFor} title={ui.whoForTitle} />
      <div className="mt-14 grid gap-6 md:grid-cols-3">
        {content.whoFor.map((profile, i) => (
          <Reveal key={profile.title} delay={i * 0.1} className="border-t-2 border-gold bg-cream p-8">
            <h3 className="font-serif text-2xl leading-snug">{profile.title}</h3>
            <p className="mt-3 text-stone">{profile.text}</p>
          </Reveal>
        ))}
      </div>
    </Section>
  );
}

function HowItWorks({ content, ui }: { content: LocalizedService; ui: ServiceUi }) {
  return (
    <section className="bg-forest text-cream">
      <div className="mx-auto grid max-w-7xl gap-14 px-5 py-20 md:px-8 md:py-28 lg:grid-cols-[1.4fr_1fr] lg:gap-20">
        <div>
          <p className="eyebrow text-gold-light">{ui.howItWorks}</p>
          <ol className="mt-10 grid gap-10 sm:grid-cols-2">
            {content.steps.map((step, i) => (
              <li key={step.title}>
                <Reveal delay={i * 0.08} className="border-t border-cream/20 pt-6">
                  <span className="font-serif text-4xl text-gold-light/80">{String(i + 1).padStart(2, "0")}</span>
                  <h3 className="mt-3 font-serif text-2xl">{step.title}</h3>
                  <p className="mt-2 text-cream/70">{step.text}</p>
                </Reveal>
              </li>
            ))}
          </ol>
        </div>
        <Reveal className="self-start border border-gold/50 p-8 md:p-10">
          <p className="eyebrow text-gold-light">{ui.howWeCharge}</p>
          <p className="mt-5 font-serif text-3xl leading-snug">{content.charge.model}</p>
          <p className="mt-4 text-cream/70">{content.charge.text}</p>
          <p className="mt-8 text-xs tracking-[0.18em] text-gold-light">{ui.feePending}</p>
        </Reveal>
      </div>
    </section>
  );
}

function Related({ lang, slugs, ui }: { lang: Locale; slugs: ServiceSlug[]; ui: ServiceUi }) {
  return (
    <Section tone="sand">
      <p className="eyebrow text-gold-ink">{ui.related}</p>
      <div className="mt-8 grid gap-4 md:grid-cols-3">
        {slugs.map((slug) => (
          <Link
            key={slug}
            href={localizedPath(lang, `/services/${slug}`)}
            className="group flex h-full flex-col justify-between border border-ink/10 bg-cream p-7 transition hover:border-forest"
          >
            <div>
              <h3 className="font-serif text-2xl leading-snug transition group-hover:text-forest">{services[slug].name[lang]}</h3>
              <p className="mt-3 text-sm text-stone">{services[slug].line[lang]}</p>
            </div>
            <span className="eyebrow mt-8 flex items-center gap-2 text-[0.62rem] text-gold-ink">
              {ui.discover} <ArrowUpRight size={14} strokeWidth={1.5} className="transition group-hover:-translate-y-0.5 group-hover:translate-x-0.5" />
            </span>
          </Link>
        ))}
      </div>
    </Section>
  );
}

/** Extra block specific to each division. */
async function DivisionExtra({ slug, lang, ui }: { slug: ServiceSlug; lang: Locale; ui: ServiceUi }) {
  if (slug === "luxury-real-estate") {
    const featured = (await fetchProperties({ lang, featured: true, pageSize: 3 }))?.items ?? [];
    if (!featured.length) return null;
    const copy = getPropertyCopy(lang);
    return (
      <Section>
        <div className="flex flex-wrap items-end justify-between gap-6">
          <h2 className="font-serif text-4xl md:text-5xl">{ui.featured}</h2>
          <div className="flex flex-wrap gap-6">
            <Link href={localizedPath(lang, "/properties")} className="eyebrow inline-flex items-center gap-2 border-b border-gold pb-1.5 text-ink hover:text-gold-ink">
              {ui.allProperties} <ArrowRight size={14} strokeWidth={1.5} />
            </Link>
            <Link href={localizedPath(lang, "/sell-with-us")} className="eyebrow inline-flex items-center gap-2 border-b border-gold pb-1.5 text-ink hover:text-gold-ink">
              {ui.sellWithUs} <ArrowRight size={14} strokeWidth={1.5} />
            </Link>
          </div>
        </div>
        <div className="mt-12 grid gap-x-8 gap-y-14 md:grid-cols-2 lg:grid-cols-3">
          {featured.map((item) => (
            <PropertyCard key={item.slug} property={item} lang={lang} copy={copy} />
          ))}
        </div>
      </Section>
    );
  }

  if (slug === "architecture-development") {
    const placeholders = [images.heroSlides[0], images.heroSlides[3], images.about];
    return (
      <Section>
        <h2 className="font-serif text-4xl md:text-5xl">{ui.projects}</h2>
        <div className="mt-12 grid gap-6 md:grid-cols-3">
          {placeholders.map((src, i) => (
            <figure key={i}>
              <div className="relative">
                <RevealImage src={src} alt="" sizes="(min-width: 768px) 33vw, 100vw" className="aspect-[4/5]" delay={i * 0.1} />
              </div>
              <figcaption className="mt-4 text-xs tracking-[0.16em] text-stone">{ui.projectPending}</figcaption>
            </figure>
          ))}
        </div>
      </Section>
    );
  }

  if (slug === "investment-opportunities") {
    return (
      <InvestorProfileForm
        copy={ui.investor}
        zones={locationSlugs.map((z) => ({ value: z, label: locations[z].name[lang] }))}
        lang={lang}
        messages={getFormMessages(lang)}
      />
    );
  }

  if (slug === "property-management-concierge") {
    return (
      <Section>
        <div className="grid gap-6 md:grid-cols-2">
          <Reveal className="border border-ink/10 bg-white/60 p-8 md:p-10">
            <p className="eyebrow text-gold-ink">{ui.reports}</p>
            <p className="mt-5 font-serif text-2xl leading-snug">{ui.reportsText}</p>
          </Reveal>
          <Reveal delay={0.1} className="bg-ink p-8 text-cream md:p-10">
            <p className="eyebrow text-gold-light">{ui.mifinka}</p>
            <p className="mt-5 font-serif text-2xl leading-snug">{ui.mifinkaText}</p>
            <a href="https://mifinka.com" target="_blank" rel="noopener" className="eyebrow mt-8 inline-flex items-center gap-2 text-gold-light hover:text-cream">
              mifinka.com <ArrowUpRight size={14} strokeWidth={1.5} />
            </a>
          </Reveal>
        </div>
      </Section>
    );
  }

  return null;
}

export default async function ServicePage({ params }: { params: Params }) {
  const r = await resolve(params);
  if (!r) notFound();
  const { lang, slug } = r;
  const content = getServiceContent(slug, lang);
  const ui = getServiceUi(lang);
  const name = services[slug].name[lang];
  const showNotice = servicesWithLegalNotice.includes(slug);

  return (
    <main>
      <PageHero
        lang={lang}
        eyebrow={lang === "en" ? "Services" : "Servicios"}
        title={name}
        intro={content.value}
        crumbs={buildCrumbs(lang, `/services/${slug}`, name)}
        image={content.image}
      />

      {showNotice && (
        <div className="bg-sand">
          <p className="mx-auto max-w-7xl px-5 py-5 text-sm leading-relaxed text-ink/75 md:px-8">{legalNotice[lang]}</p>
        </div>
      )}

      <Overview content={content} ui={ui} />
      <WhoFor content={content} ui={ui} />
      <HowItWorks content={content} ui={ui} />
      <DivisionExtra slug={slug} lang={lang} ui={ui} />

      <Section>
        <div className="grid gap-10 lg:grid-cols-[1fr_2fr] lg:gap-16">
          <h2 className="font-serif text-4xl leading-tight md:text-5xl">{ui.faq}</h2>
          <FaqList items={content.faqs.map((f) => ({ q: f.q, a: f.a, reviewNote: f.review ? ui.review[f.review] : undefined }))} />
        </div>
        {showNotice && <p className="mt-14 max-w-3xl border-l-2 border-gold pl-5 text-sm leading-relaxed text-stone">{legalNotice[lang]}</p>}
      </Section>

      <Related lang={lang} slugs={content.related} ui={ui} />
      <ClosingCta lang={lang} copy={getLayoutCopy(lang)} />
    </main>
  );
}
