"use client";

import { useState } from "react";
import { ArrowRight, CalendarDays, Clock3, FileText, Share2, ExternalLink } from "lucide-react";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import StickyMobileCTA from "@/components/StickyMobileCTA";
import { Badge } from "@/components/ui/badge";
import WpImage from "@/components/ui/WpImage";
import { sanitizeWpHtml } from "@/lib/sanitizeHtml";
import type { WpImage as WpImageData } from "@/lib/wp/types";
import type { TocEntry, BlogCard } from "@/lib/blog/content";

export interface BlogArticleViewData {
  slug: string;
  title: string;
  description: string;
  category: string;
  date: string;
  readTime: string;
  author: string;
  image: WpImageData | null;
  imageAlt: string;
  enBref: string[];
  contentHtml: string;
  toc: TocEntry[];
  sources: { reference: string; url: string }[];
  related: BlogCard[];
}

const PrimaryCTA = ({ href, children }: { href: string; children: string }) => (
  <a
    href={href}
    className="group inline-flex w-full items-center justify-center gap-2 rounded-full cta-gradient py-2.5 pl-6 pr-2 font-semibold text-white sm:w-auto"
  >
    <span className="text-sm">{children}</span>
    <span className="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 transition-transform duration-500 group-hover:translate-x-0.5">
      <ArrowRight className="h-3.5 w-3.5" />
    </span>
  </a>
);

const SecondaryCTA = ({ href, children, light = false }: { href: string; children: string; light?: boolean }) => (
  <a
    href={href}
    className={`group inline-flex items-center justify-center gap-2 rounded-full border py-2.5 pl-6 pr-2 font-semibold transition-colors ${
      light
        ? "border-white/25 bg-white/5 text-white hover:bg-white/10"
        : "border-primary/25 bg-white text-primary hover:bg-primary/5"
    }`}
  >
    <span className="text-sm">{children}</span>
    <span className={`flex h-8 w-8 items-center justify-center rounded-full transition-transform duration-500 group-hover:translate-x-0.5 ${light ? "bg-white/12" : "bg-primary/10"}`}>
      <ArrowRight className="h-3.5 w-3.5" />
    </span>
  </a>
);

const ArticleTableOfContents = ({ toc }: { toc: TocEntry[] }) => {
  const [expanded, setExpanded] = useState(false);
  const visible = expanded ? toc : toc.slice(0, 6);

  return (
    <section className="mx-auto w-full max-w-5xl px-4 sm:px-6 lg:px-8">
      <div className="rounded-lg border border-border bg-card p-5 shadow-sm lg:p-6">
        <div className="mb-5 flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
          <div>
            <p className="font-body text-xs font-bold uppercase tracking-[0.18em] text-primary/65">Dans cet article</p>
            <h2 className="mt-1 font-satoshi text-xl font-black tracking-tight text-foreground">Sommaire</h2>
          </div>
          <p className="font-body text-sm text-foreground/50">{toc.length} parties</p>
        </div>
        <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
          {visible.map((item, index) => (
            <a
              key={item.id}
              href={`#${item.id}`}
              className="group rounded-lg border border-border bg-background p-4 transition-colors hover:border-primary/25 hover:bg-primary/5"
            >
              <span className="font-satoshi text-xs font-black text-primary/55">{String(index + 1).padStart(2, "0")}</span>
              <span className="mt-2 block font-body text-sm font-bold leading-snug text-foreground/76 group-hover:text-primary">
                {item.title}
              </span>
            </a>
          ))}
        </div>
        {toc.length > 6 && (
          <button
            type="button"
            onClick={() => setExpanded((open) => !open)}
            className="mt-4 inline-flex items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-4 py-2.5 font-body text-sm font-bold text-primary transition-colors hover:bg-primary/10"
          >
            {expanded ? "Voir moins" : `Voir plus (${toc.length - 6})`}
          </button>
        )}
      </div>
    </section>
  );
};

const BlogArticle = ({ article }: { article: BlogArticleViewData }) => {
  const canonical = `https://www.covalba.fr/blog/${article.slug}`;

  return (
    <div className="min-h-screen bg-background">
      <Navbar />

      <main>
        <article>
          <header className="bg-navy pb-8 pt-24 text-white lg:pb-10 lg:pt-28">
            <div className="container mx-auto px-4 lg:px-8">
              <div className="grid gap-7 lg:grid-cols-[minmax(0,0.88fr)_minmax(380px,0.64fr)] lg:items-center">
                <div>
                  <div className="mb-5 flex flex-wrap items-center gap-3">
                    <a
                      href="/guides"
                      className="inline-flex items-center gap-2 font-body text-sm font-semibold text-white/62 transition-colors hover:text-white"
                    >
                      <ArrowRight className="h-4 w-4 rotate-180" />
                      Retour aux guides
                    </a>
                    <Badge className="border-white/12 bg-white/10 text-white">{article.category}</Badge>
                  </div>
                  <h1 className="max-w-4xl font-satoshi text-[2.08rem] font-black leading-[1.03] tracking-tight text-white md:text-5xl lg:text-6xl">
                    {article.title}
                  </h1>
                  {article.description && (
                    <p className="mt-5 max-w-3xl font-body text-base leading-relaxed text-white/68 md:text-lg">
                      {article.description}
                    </p>
                  )}
                  <div className="mt-6 flex flex-wrap items-center gap-4 font-body text-sm text-white/55">
                    {article.date && (
                      <span className="inline-flex items-center gap-1.5">
                        <CalendarDays className="h-4 w-4" />
                        {article.date}
                      </span>
                    )}
                    <span className="inline-flex items-center gap-1.5">
                      <Clock3 className="h-4 w-4" />
                      {article.readTime}
                    </span>
                    {article.author && (
                      <span className="inline-flex items-center gap-1.5">
                        <FileText className="h-4 w-4" />
                        {article.author}
                      </span>
                    )}
                  </div>
                  <div className="mt-7 grid grid-cols-[1fr_auto] gap-3 sm:flex sm:flex-row">
                    <PrimaryCTA href="/diagnostic">Demander un devis</PrimaryCTA>
                    <a
                      href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(canonical)}`}
                      aria-label="Partager l’article"
                      className="inline-flex h-[52px] w-[52px] items-center justify-center gap-2 rounded-full border border-white/15 bg-white/10 px-0 py-3 font-body text-sm font-bold text-white/80 transition-colors hover:bg-white/15 hover:text-white sm:h-auto sm:w-auto sm:px-5"
                    >
                      <Share2 className="h-4 w-4" />
                      <span className="hidden sm:inline">Partager</span>
                    </a>
                  </div>
                </div>

                {article.image && (
                  <figure className="overflow-hidden rounded-lg border border-border bg-card shadow-[0_24px_80px_rgba(0,45,53,0.14)]">
                    <div className="relative aspect-[16/8] w-full sm:aspect-[16/10] lg:aspect-[16/11]">
                      <WpImage image={article.image} alt={article.imageAlt} fill priority className="w-full object-cover" />
                    </div>
                  </figure>
                )}
              </div>
            </div>
          </header>

          {article.toc.length > 0 && (
            <section className="bg-offwhite pb-8 pt-4 lg:pb-12 lg:pt-8">
              <ArticleTableOfContents toc={article.toc} />
            </section>
          )}

          <section className="bg-background py-12 lg:py-20">
            <div className="mx-auto w-full max-w-[820px] px-4 sm:px-6 lg:px-8">
              {article.enBref.length > 0 && (
                <div className="not-prose mb-12 rounded-lg border border-primary/15 bg-offwhite p-6 shadow-sm lg:p-7">
                  <p className="mb-5 font-body text-xs font-bold uppercase tracking-[0.18em] text-primary/70">En bref</p>
                  <div className="grid gap-4">
                    {article.enBref.map((point) => (
                      <div key={point} className="flex gap-3">
                        <span className="mt-2.5 h-2 w-2 shrink-0 rounded-full bg-primary" aria-hidden="true" />
                        <p className="font-body text-[0.98rem] leading-7 text-foreground/68">{point}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className="blog-prose" dangerouslySetInnerHTML={{ __html: sanitizeWpHtml(article.contentHtml) }} />

              {article.sources.length > 0 && (
                <section className="mt-14 border-t border-border/70 pt-10">
                  <Badge className="mb-4 bg-teal-light text-primary">Bibliographie</Badge>
                  <h2 className="mb-6 font-satoshi text-2xl font-black tracking-tight text-foreground">Sources</h2>
                  <ol className="space-y-4">
                    {article.sources.map((s, i) => (
                      <li key={i} className="font-body text-sm leading-7 text-foreground/62">
                        {s.reference}
                        {s.url && (
                          <>
                            {" "}
                            <a
                              href={s.url}
                              rel="noopener noreferrer nofollow"
                              target="_blank"
                              className="inline-flex items-center gap-1 font-semibold text-primary hover:underline"
                            >
                              Lien
                              <ExternalLink className="h-3 w-3" />
                            </a>
                          </>
                        )}
                      </li>
                    ))}
                  </ol>
                </section>
              )}
            </div>
          </section>

          <section className="bg-navy py-16 text-white lg:py-20">
            <div className="container mx-auto px-4 lg:px-8">
              <div className="grid gap-8 lg:grid-cols-[1fr_0.82fr] lg:items-center">
                <div>
                  <Badge className="mb-4 border-white/12 bg-white/10 text-white">Diagnostic gratuit</Badge>
                  <h2 className="font-satoshi text-4xl font-black tracking-tight lg:text-5xl">
                    Un projet de toiture ou de cool roof ?
                  </h2>
                  <p className="mt-5 max-w-2xl font-body text-lg leading-relaxed text-white/62">
                    Covalba vous aide à cadrer l’état du support, le système adapté et les économies attendues, devis et
                    diagnostic à l’appui.
                  </p>
                </div>
                <div className="flex flex-col gap-3 sm:flex-row lg:justify-end">
                  <PrimaryCTA href="/diagnostic">Demander un devis</PrimaryCTA>
                  <SecondaryCTA href="/contact" light>
                    Contacter Covalba
                  </SecondaryCTA>
                </div>
              </div>
            </div>
          </section>

          {article.related.length > 0 && (
            <section className="bg-card py-16 lg:py-20">
              <div className="container mx-auto px-4 lg:px-8">
                <div className="mb-9 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
                  <div>
                    <Badge className="mb-4 bg-teal-light text-primary">À lire aussi</Badge>
                    <h2 className="font-satoshi text-3xl font-black tracking-tight text-foreground">Guides proches de ce sujet.</h2>
                  </div>
                  <a href="/guides" className="group inline-flex items-center gap-2 font-body text-sm font-semibold text-primary">
                    Tous les articles
                    <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" />
                  </a>
                </div>
                <div className="grid gap-5 md:grid-cols-3">
                  {article.related.map((related) => (
                    <a
                      key={related.href}
                      href={related.href}
                      className="group rounded-lg border border-border bg-background p-5 transition-all hover:-translate-y-0.5 hover:border-primary/25 hover:shadow-sm"
                    >
                      <span className="rounded-full bg-primary/10 px-3 py-1 font-body text-[11px] font-bold uppercase tracking-[0.12em] text-primary">
                        {related.category}
                      </span>
                      <h3 className="mt-4 font-satoshi text-xl font-black leading-tight tracking-tight text-foreground group-hover:text-primary">
                        {related.title}
                      </h3>
                      <span className="mt-6 inline-flex items-center gap-1.5 font-body text-sm font-semibold text-primary">
                        Lire l’article
                        <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" />
                      </span>
                    </a>
                  ))}
                </div>
              </div>
            </section>
          )}
        </article>
      </main>

      <Footer />
      <StickyMobileCTA label="Devis toiture" href="/diagnostic" phoneHref="tel:+33238775708" />
    </div>
  );
};

export default BlogArticle;
