import type { Metadata } from "next";
import type { CSSProperties } from "react";
import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, ArrowRight, ArrowUpRight, Check } from "lucide-react";
import { SiteFrame } from "@/app/components/SiteFrame/SiteFrame";
import { JsonLd } from "@/app/lib/structured-data";
import { AnimatedDiv, AnimatedSection } from "@/app/components/Motion/AnimatedSection";
import { getAllCaseStudies, getCaseStudyBySlug } from "@/app/lib/data/case-studies";
import styles from "./case-study.module.css";

export async function generateStaticParams() {
  return getAllCaseStudies().map((study) => ({ slug: study.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const study = getCaseStudyBySlug(slug);

  if (!study) {
    return { title: "Case Study Not Found" };
  }

  const title = `${study.client} — Case Study`;

  return {
    title,
    description: study.summary,
    alternates: { canonical: `/case-studies/${study.slug}` },
    openGraph: {
      title,
      description: study.summary,
      url: `/case-studies/${study.slug}`,
      type: "article",
    },
  };
}

export default async function CaseStudyPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const study = getCaseStudyBySlug(slug);

  if (!study) {
    notFound();
  }

  const themedStyle: CSSProperties = {
    ["--accent-start" as string]: study.accentStart,
    ["--accent-end" as string]: study.accentEnd,
    ["--accent-glow" as string]: study.accentGlow,
  };

  const canonical = `https://meliorate.pro/case-studies/${study.slug}`;

  const facts = [
    { label: "Client", value: study.client },
    { label: "Sector", value: study.sector },
    { label: "Engagement", value: study.engagement },
    { label: "Period", value: study.period },
  ];

  return (
    <SiteFrame>
      <JsonLd
        data={{
          "@context": "https://schema.org",
          "@type": "BreadcrumbList",
          itemListElement: [
            { "@type": "ListItem", position: 1, name: "Home", item: "https://meliorate.pro" },
            {
              "@type": "ListItem",
              position: 2,
              name: "Case Studies",
              item: "https://meliorate.pro/case-studies",
            },
            { "@type": "ListItem", position: 3, name: study.client, item: canonical },
          ],
        }}
      />
      <JsonLd
        data={{
          "@context": "https://schema.org",
          "@type": "Article",
          headline: `${study.client} — ${study.headline}`,
          description: study.summary,
          url: canonical,
          mainEntityOfPage: canonical,
          author: { "@type": "Organization", name: "Meliorate", url: "https://meliorate.pro" },
          publisher: { "@type": "Organization", name: "Meliorate", url: "https://meliorate.pro" },
          about: { "@type": "Organization", name: study.client, url: study.siteHref },
          keywords: study.stack.join(", "),
        }}
      />

      <section className={styles.pageSection} style={themedStyle}>
        <div className={styles.container}>
          <AnimatedDiv>
            <Link href="/case-studies" className={styles.backLink}>
              <ArrowLeft size={15} /> All case studies
            </Link>

            <div className={styles.hero}>
              <span className={styles.eyebrow}>Case Study</span>
              <h1 className={styles.title}>{study.client}</h1>
              <p className={styles.headline}>{study.headline}</p>
              <p className={styles.summary}>{study.summary}</p>

              <ul className={styles.stack}>
                {study.stack.map((item) => (
                  <li key={item} className={styles.stackItem}>
                    {item}
                  </li>
                ))}
              </ul>

              <div className={styles.heroActions}>
                <Link
                  href={study.siteHref}
                  target="_blank"
                  rel="noreferrer"
                  className={styles.primaryButton}
                >
                  Visit {study.siteLabel} <ArrowUpRight size={17} />
                </Link>
                <Link href="/contact" className={styles.secondaryButton}>
                  Discuss a Build <ArrowRight size={16} />
                </Link>
              </div>
            </div>
          </AnimatedDiv>

          <AnimatedSection className={styles.factGrid}>
            {facts.map((fact) => (
              <article key={fact.label} className={styles.factCard}>
                <p className={styles.factLabel}>{fact.label}</p>
                <p className={styles.factValue}>{fact.value}</p>
              </article>
            ))}
          </AnimatedSection>

          <AnimatedSection className={styles.section}>
            <p className={styles.sectionLabel}>The brief</p>
            <h2 className={styles.sectionTitle}>What the business needed</h2>
            <div className={styles.prose}>
              {study.context.map((paragraph) => (
                <p key={paragraph}>{paragraph}</p>
              ))}
            </div>
          </AnimatedSection>

          <AnimatedSection className={styles.section}>
            <p className={styles.sectionLabel}>Constraints</p>
            <h2 className={styles.sectionTitle}>What ruled out the easy design</h2>
            <div className={styles.prose}>
              <p>{study.constraintsIntro}</p>
            </div>
            <ol className={styles.constraintList}>
              {study.constraints.map((constraint) => (
                <li key={constraint.title} className={styles.constraintItem}>
                  <div>
                    <h3 className={styles.constraintTitle}>{constraint.title}</h3>
                    <p className={styles.constraintDetail}>{constraint.detail}</p>
                  </div>
                </li>
              ))}
            </ol>
          </AnimatedSection>

          <AnimatedSection className={styles.pivot}>
            <p className={styles.sectionLabel}>Approach</p>
            <h2 className={styles.pivotTitle}>{study.pivot.title}</h2>
            <div className={styles.prose}>
              {study.pivot.body.map((paragraph) => (
                <p key={paragraph}>{paragraph}</p>
              ))}
            </div>
          </AnimatedSection>

          <AnimatedSection className={styles.section}>
            <p className={styles.sectionLabel}>What we built</p>
            <h2 className={styles.sectionTitle}>The system, part by part</h2>
            <div className={styles.buildGrid}>
              {study.build.map((item) => (
                <article key={item.title} className={styles.buildCard}>
                  <h3 className={styles.buildTitle}>{item.title}</h3>
                  <p className={styles.buildDetail}>{item.detail}</p>
                </article>
              ))}
            </div>
          </AnimatedSection>

          <AnimatedSection className={styles.section}>
            <p className={styles.sectionLabel}>Engineering decisions</p>
            <h2 className={styles.sectionTitle}>Four choices we would defend in review</h2>
            <div className={styles.decisionList}>
              {study.decisions.map((decision) => (
                <article key={decision.title} className={styles.decisionCard}>
                  <h3 className={styles.decisionTitle}>{decision.title}</h3>
                  <div className={styles.decisionRow}>
                    <div className={styles.decisionCell}>
                      <p className={styles.decisionCellLabel}>The problem</p>
                      <p className={styles.decisionCellText}>{decision.problem}</p>
                    </div>
                    <div className={styles.decisionCell}>
                      <p
                        className={`${styles.decisionCellLabel} ${styles.decisionCellLabelSolution}`}
                      >
                        What we did
                      </p>
                      <p className={styles.decisionCellText}>{decision.solution}</p>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </AnimatedSection>

          <AnimatedSection className={styles.section}>
            <p className={styles.sectionLabel}>Scale</p>
            <h2 className={styles.sectionTitle}>What shipped, by the numbers</h2>
            <div className={styles.metricsGrid}>
              {study.metrics.map((metric) => (
                <article key={metric.label} className={styles.metricCard}>
                  <p className={styles.metricValue}>{metric.value}</p>
                  <h3 className={styles.metricLabel}>{metric.label}</h3>
                  <p className={styles.metricText}>{metric.detail}</p>
                </article>
              ))}
            </div>
          </AnimatedSection>

          <AnimatedSection className={styles.section}>
            <p className={styles.sectionLabel}>Outcome</p>
            <h2 className={styles.sectionTitle}>Where it stands</h2>
            <div className={styles.outcomeBlock}>
              <ul className={styles.outcomeList}>
                {study.outcome.map((item) => (
                  <li key={item} className={styles.outcomeItem}>
                    <Check size={17} />
                    <span>{item}</span>
                  </li>
                ))}
              </ul>

              {study.quote && (
                <blockquote className={styles.quote}>
                  <p className={styles.quoteText}>&ldquo;{study.quote.text}&rdquo;</p>
                  <p className={styles.quoteSource}>
                    {study.quote.sourceHref ? (
                      <a href={study.quote.sourceHref} target="_blank" rel="noreferrer">
                        {study.quote.source}
                      </a>
                    ) : (
                      study.quote.source
                    )}
                  </p>
                </blockquote>
              )}
            </div>
          </AnimatedSection>

          <AnimatedSection className={styles.ctaBand}>
            <div>
              <p className={styles.ctaEyebrow}>Similar problem</p>
              <h2>Need a system that has to be right the second time it runs?</h2>
              <p>
                Idempotency, custody, settlement, and audit trails are the parts that are expensive
                to retrofit. We would rather design them in.
              </p>
            </div>
            <Link href="/contact" className={styles.primaryButton}>
              Contact Meliorate <ArrowRight size={17} />
            </Link>
          </AnimatedSection>
        </div>
      </section>
    </SiteFrame>
  );
}
