import { notFound } from "next/navigation";
import { ExternalLink } from "lucide-react";

import { Badge, CmsImage, Container, CTASection, ErrorState, JsonLd, PageHero, RichText, Section, SectionHeading } from "@/components";
import { api } from "@/lib/api";
import { breadcrumbSchema, caseStudySchema, createMetadata } from "@/lib/seo";

export const revalidate = 300;

type DetailParams = { params: Promise<{ slug: string }> };
type CaseStudyMetric = {
  label?: string;
  value?: string;
  detail?: string;
};

function hasRichTextContent(content: string | null | undefined) {
  return Boolean(content?.replace(/<[^>]*>/g, "").trim());
}

function hasMetricContent(metric: CaseStudyMetric) {
  return Boolean(metric.label?.trim() || metric.value?.trim() || metric.detail?.trim());
}

function getVideoEmbedUrl(videoUrl: string | null) {
  if (!videoUrl) return null;

  try {
    const url = new URL(videoUrl);

    if (url.hostname.includes("youtube.com")) {
      const videoId = url.searchParams.get("v");
      return videoId ? `https://www.youtube-nocookie.com/embed/${videoId}` : null;
    }

    if (url.hostname.includes("youtu.be")) {
      const videoId = url.pathname.replace("/", "");
      return videoId ? `https://www.youtube-nocookie.com/embed/${videoId}` : null;
    }

    if (url.hostname.includes("vimeo.com")) {
      const videoId = url.pathname.split("/").filter(Boolean).at(-1);
      return videoId ? `https://player.vimeo.com/video/${videoId}` : null;
    }
  } catch {
    return null;
  }

  return null;
}

function isDirectVideoUrl(videoUrl: string | null) {
  return Boolean(videoUrl && /\.(mp4|webm|ogg)(\?|#|$)/i.test(videoUrl));
}

export async function generateMetadata({ params }: DetailParams) {
  const { slug } = await params;
  const result = await api.caseStudy(slug);

  if (!result.ok) {
    return createMetadata({
      title: "Referenca nije pronađena",
      description: "Tražena referenca nije pronađena ili nije objavljena.",
      path: `/reference/${slug}`,
    });
  }

  const item = result.data;

  return createMetadata({
    title: item.meta_title ?? item.title,
    description: item.meta_description ?? item.short_description,
    path: `/reference/${item.slug}`,
    image: item.featured_image,
  });
}

export default async function ReferenceDetailPage({ params }: DetailParams) {
  const { slug } = await params;
  const result = await api.caseStudy(slug);

  if (!result.ok) {
    if (result.status === 404) {
      notFound();
    }

    return <main className="py-16"><Container><ErrorState message={result.message} /></Container></main>;
  }

  const item = result.data;
  const metrics = item.metrics.filter(hasMetricContent);
  const videoEmbedUrl = getVideoEmbedUrl(item.video_url);
  const hasDirectVideo = isDirectVideoUrl(item.video_url);
  const hasTestimonial = Boolean(item.client_testimonial?.trim());

  return (
    <main>
      <JsonLd
        data={[
          breadcrumbSchema([
            { name: "Početna", path: "/" },
            { name: "Reference", path: "/reference" },
            { name: item.title, path: `/reference/${item.slug}` },
          ]),
          caseStudySchema(item),
        ]}
      />
      <PageHero
        eyebrow={item.industry ?? "Reference"}
        title={item.title}
        description={item.short_description ?? "Detalji projekta i poslovnog konteksta."}
        primaryAction={item.website_url ? { label: "Pogledaj sajt", href: item.website_url } : { label: "Zatražite procenu sličnog projekta", href: "/kontakt", leadType: "custom_ecommerce", subject: `Upit: sličan projekat kao ${item.title}`, sourceSection: `Reference hero: ${item.title}` }}
      />
      <Section className="bg-white">
        <Container className="grid gap-10 lg:grid-cols-[0.7fr_1.3fr]">
          <aside className="rounded-lg border border-slate-200 bg-slate-50 p-6">
            <p className="text-sm font-semibold text-primary">{item.client_name ?? item.title}</p>
            <h2 className="mt-2 text-xl font-semibold text-slate-950">{item.industry ?? "Business software"}</h2>
            {item.project_type ? <p className="mt-2 text-sm leading-6 text-slate-600">{item.project_type}</p> : null}
            {item.website_url ? (
              <a
                href={item.website_url}
                target="_blank"
                rel="noopener noreferrer"
                className="mt-5 inline-flex items-center gap-2 text-sm font-semibold text-primary hover:text-primary-700"
              >
                Pogledaj sajt
                <ExternalLink aria-hidden="true" className="h-4 w-4" strokeWidth={1.8} />
              </a>
            ) : null}
            {item.key_features.length > 0 ? (
              <div className="mt-5">
                <p className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">Ključne funkcionalnosti</p>
                <div className="mt-3 flex flex-wrap gap-2">
                  {item.key_features.map((feature) => (
                    <Badge key={feature} tone="slate">{feature}</Badge>
                  ))}
                </div>
              </div>
            ) : null}
            {item.technologies.length > 0 ? (
              <div className="mt-5">
                <p className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">Tehnologije</p>
                <div className="mt-3 flex flex-wrap gap-2">
                  {item.technologies.map((technology) => (
                    <Badge key={technology} tone="slate">{technology}</Badge>
                  ))}
                </div>
              </div>
            ) : null}
          </aside>
          <div className="grid gap-10">
            <CmsImage src={item.featured_image} alt={item.title} priority />
            {hasRichTextContent(item.problem) ? (
              <div>
                <SectionHeading title="Problem" />
                <div className="mt-5"><RichText content={item.problem} /></div>
              </div>
            ) : null}
            {hasRichTextContent(item.challenge) ? (
              <div>
                <SectionHeading title="Izazov" />
                <div className="mt-5"><RichText content={item.challenge} /></div>
              </div>
            ) : null}
            {hasRichTextContent(item.solution) ? (
              <div>
                <SectionHeading title="Rešenje" />
                <div className="mt-5"><RichText content={item.solution} /></div>
              </div>
            ) : null}
            {hasRichTextContent(item.results) ? (
              <div>
                <SectionHeading title="Rezultati" />
                <div className="mt-5"><RichText content={item.results} /></div>
              </div>
            ) : null}
            {metrics.length > 0 ? (
              <div>
                <SectionHeading title="Metrike" description="Prikazujemo samo metrike koje su unete u CMS i potvrđene za ovaj projekat." />
                <div className="mt-6 grid gap-4 sm:grid-cols-2">
                  {metrics.map((metric, index) => (
                    <div key={`${metric.label ?? "metric"}-${index}`} className="rounded-lg border border-slate-200 bg-slate-50 p-5">
                      {metric.label ? <p className="text-xs font-semibold uppercase tracking-[0.14em] text-primary">{metric.label}</p> : null}
                      {metric.value ? <p className="mt-2 text-3xl font-semibold leading-tight text-slate-950">{metric.value}</p> : null}
                      {metric.detail ? <p className="mt-3 text-sm leading-6 text-slate-600">{metric.detail}</p> : null}
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
            {item.video_url ? (
              <div>
                <SectionHeading title="Video" />
                <div className="mt-5">
                  {hasDirectVideo ? (
                    <video src={item.video_url} controls className="aspect-video w-full rounded-xl border border-slate-200 bg-slate-950" />
                  ) : videoEmbedUrl ? (
                    <iframe
                      src={videoEmbedUrl}
                      title={`Video: ${item.title}`}
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                      allowFullScreen
                      className="aspect-video w-full rounded-xl border border-slate-200"
                    />
                  ) : (
                    <a
                      href={item.video_url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-2 text-sm font-semibold text-primary hover:text-primary-700"
                    >
                      Pogledaj video
                      <ExternalLink aria-hidden="true" className="h-4 w-4" strokeWidth={1.8} />
                    </a>
                  )}
                </div>
              </div>
            ) : null}
            {hasTestimonial ? (
              <blockquote className="rounded-xl border border-primary/15 bg-primary-50 p-6">
                <p className="text-lg leading-8 text-slate-800">“{item.client_testimonial}”</p>
                {(item.testimonial_author || item.testimonial_role) ? (
                  <footer className="mt-5 text-sm font-semibold text-slate-950">
                    {item.testimonial_author}
                    {item.testimonial_author && item.testimonial_role ? ", " : null}
                    {item.testimonial_role}
                  </footer>
                ) : null}
              </blockquote>
            ) : null}
          </div>
        </Container>
      </Section>
      <CTASection
        title="Želite sličan sistem?"
        description="Pošaljite nam poslovni kontekst i ključne integracije."
        actionLabel={item.cta_label ?? "Zatražite procenu sličnog projekta"}
        leadType="custom_ecommerce"
        subject={`Upit: sličan projekat kao ${item.title}`}
        sourceSection={`Reference detail: ${item.title}`}
      />
    </main>
  );
}
