import { useParams, Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Helmet } from "react-helmet-async";
import { Layout } from "@/components/layout/Layout";
import { Section } from "@/components/ui/Section";
import { SEO } from "@/components/SEO";
import { useForceLanguage } from "@/hooks/useForceLanguage";
import { useArticleBySlug, useArticles } from "@/hooks/useArticles";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { format } from "date-fns";
import { newsStrings, newsBasePathFor, newsContactPathFor, NewsLang } from "@/lib/newsStrings";
import { sv, enUS } from "date-fns/locale";
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import NotFound from "@/pages/NotFound";

const DOMAIN = "https://sutekistudios.com";

const absolute = (url?: string) =>
  !url ? `${DOMAIN}/assets/suteki-logo.png` : url.startsWith("http") ? url : `${DOMAIN}${url.startsWith("/") ? "" : "/"}${url}`;

interface NewsArticleProps { lang?: NewsLang }

const NewsArticle = ({ lang = "sv" }: NewsArticleProps) => {
  const { t } = useTranslation();
  useForceLanguage(lang);
  const { slug } = useParams<{ slug: string }>();
  const isSwedish = lang === "sv";
  const s = newsStrings[lang];
  const newsBase = newsBasePathFor(lang);
  const dateLocale = isSwedish ? sv : enUS;

  const { data: article, isLoading: articleLoading } = useArticleBySlug(slug, lang);
  const { data: allArticles = [] } = useArticles(lang);

  if (articleLoading) {
    return (
      <Layout>
        <div className="min-h-[70vh] flex items-center justify-center">
          <div className="animate-pulse space-y-4 max-w-2xl w-full px-6">
            <div className="h-8 bg-muted rounded w-3/4" />
            <div className="h-4 bg-muted rounded w-1/2" />
            <div className="h-64 bg-muted rounded" />
          </div>
        </div>
      </Layout>
    );
  }

  if (!article) {
    return <NotFound />;
  }

  const relatedArticles = allArticles
    .filter((a) => a.category === article.category && a.id !== article.id)
    .slice(0, 2);

  const svUrl = `${DOMAIN}/nyheter/${article.slug}`;
  const enUrl = `${DOMAIN}/en/news/${article.slug}`;
  const canonical = isSwedish ? svUrl : enUrl;
  const heroAbsolute = absolute(article.heroImage);

  return (
    <Layout>
      <SEO
        title={`${article.title} | Suteki Studios`}
        description={article.excerpt}
        lang={lang}
        canonicalUrl={canonical}
        alternateSv={article.hasEnglish ? svUrl : undefined}
        alternateEn={article.hasEnglish ? enUrl : undefined}
        alternateXDefault={article.hasEnglish ? svUrl : undefined}
        ogType="article"
      />

      <Helmet>
        <meta property="og:image" content={heroAbsolute} />
        <meta name="twitter:image" content={heroAbsolute} />
        <script type="application/ld+json">{JSON.stringify({
          "@context": "https://schema.org",
          "@type": "BreadcrumbList",
          itemListElement: [
            { "@type": "ListItem", position: 1, name: s.breadcrumbHome, item: isSwedish ? `${DOMAIN}/` : `${DOMAIN}/en` },
            { "@type": "ListItem", position: 2, name: s.breadcrumbNews, item: `${DOMAIN}${newsBase}` },
            { "@type": "ListItem", position: 3, name: article.title, item: canonical },
          ],
        })}</script>
        <script type="application/ld+json">{JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Article",
          headline: article.title,
          description: article.excerpt,
          image: heroAbsolute,
          inLanguage: isSwedish ? "sv-SE" : "en",
          datePublished: article.publishedAt,
          dateModified: article.publishedAt,
          author: { "@type": "Organization", name: "Suteki Studios" },
          publisher: {
            "@type": "Organization",
            name: "Suteki Studios",
            logo: { "@type": "ImageObject", url: `${DOMAIN}/assets/suteki-logo.png` },
          },
          mainEntityOfPage: canonical,
        })}</script>
      </Helmet>

      {/* Hero */}
      <section className="relative min-h-[70vh] flex items-end" data-hero="true">
        <img src={article.heroImage} alt={article.title} className="absolute inset-0 w-full h-full object-cover" />
        <div className="absolute inset-0" style={{ background: "linear-gradient(to top, rgba(8,12,20,0.95) 0%, rgba(8,12,20,0.50) 50%, rgba(8,12,20,0.30) 100%)" }} />
        <div className="relative z-10 container mx-auto px-6 lg:px-8 pb-20 pt-40">
          <div className="max-w-4xl">
            <Link to={newsBase} className="inline-flex items-center gap-2 hero-text-muted hover:text-white transition-colors mb-8 text-sm">
              <ArrowLeft className="w-4 h-4" />
              {s.backToNews}
            </Link>

            <div className="flex items-center gap-3 mb-6 flex-wrap">
              <span className="px-2.5 py-0.5 text-[11px] font-medium bg-white/15 text-white rounded-full">{article.category}</span>
              <span className="text-sm hero-text-muted">
                {format(new Date(article.publishedAt), isSwedish ? "d MMMM yyyy" : "MMMM d, yyyy", { locale: dateLocale })}
              </span>
              <span className="text-sm hero-text-muted">• {article.readTime} {s.readTime}</span>
            </div>

            <h1 className="display mb-6 hero-text-white">{article.title}</h1>

            {article.subtitle && (
              <p className="text-xl hero-text-body mb-4">{article.subtitle}</p>
            )}

            <p className="text-lg hero-text-muted max-w-2xl">{article.excerpt}</p>
          </div>
        </div>
      </section>

      {/* YouTube Video */}
      {article.youtubeVideoId && (
        <Section className="section-white !py-12">
          <div className="max-w-4xl mx-auto">
            <div className="aspect-video rounded-lg overflow-hidden bg-black">
              <iframe
                src={`https://www.youtube.com/embed/${article.youtubeVideoId}`}
                title="Video"
                className="w-full h-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              />
            </div>
          </div>
        </Section>
      )}

      {/* Article Content */}
      <Section className="section-white">
        <div className="max-w-4xl mx-auto">
          <article className="prose prose-lg max-w-none 
            prose-headings:font-semibold 
            prose-h2:text-2xl prose-h2:mt-12 prose-h2:mb-6
            prose-h3:text-xl prose-h3:mt-8 prose-h3:mb-4
            prose-p:leading-relaxed prose-p:mb-4
            prose-li:leading-relaxed
            prose-ul:my-4 prose-ul:pl-6 prose-ul:list-disc
            prose-ol:my-4 prose-ol:pl-6 prose-ol:list-decimal
            prose-strong:font-semibold
            prose-hr:my-10
            prose-a:no-underline hover:prose-a:underline
            [&_iframe]:w-full [&_iframe]:aspect-video [&_iframe]:rounded-lg [&_iframe]:my-6
          "
          style={{
            '--tw-prose-headings': '#0B1A33',
            '--tw-prose-body': 'rgba(11,26,51,0.85)',
            '--tw-prose-bold': '#0B1A33',
            '--tw-prose-links': 'hsl(220 91% 54%)',
            '--tw-prose-hr': 'hsl(220 13% 91%)',
            '--tw-prose-bullets': 'rgba(11,26,51,0.5)',
            '--tw-prose-counters': 'rgba(11,26,51,0.5)',
          } as React.CSSProperties}
          >
            <ReactMarkdown rehypePlugins={[rehypeRaw]}>{article.content}</ReactMarkdown>
          </article>
        </div>
      </Section>

      {/* CTA */}
      <section className="section-dark py-[var(--space-section)]" data-theme="dark">
        <div className="container mx-auto px-6 lg:px-8">
          <div className="max-w-2xl mx-auto text-center">
            <h2 className="mb-5">{s.ctaTitle}</h2>
            <p className="text-lg mb-10 leading-relaxed" style={{ color: 'rgba(226,232,240,0.7)' }}>
              {s.ctaDescription}
            </p>
            <Link to={newsContactPathFor(lang)} className="btn-white inline-flex items-center gap-2">
              {s.ctaButton}
              <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        </div>
      </section>

      {/* Related Articles */}
      {relatedArticles.length > 0 && (
        <Section className="section-beige">
          <h2 className="text-2xl font-semibold mb-8 text-foreground">{s.moreArticles}</h2>
          <div className="grid md:grid-cols-2 gap-6">
            {relatedArticles.map((relatedArticle) => (
              <Link key={relatedArticle.id} to={`${newsBase}/${relatedArticle.slug}`}
                className="group enterprise-card overflow-hidden"
              >
                <div className="aspect-[16/9] overflow-hidden">
                  <img src={relatedArticle.heroImage} alt={relatedArticle.title}
                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700" loading="lazy" />
                </div>
                <div className="p-6">
                  <div className="flex items-center gap-3 mb-4">
                    <span className="px-2 py-0.5 text-[11px] font-medium bg-secondary text-secondary-foreground rounded-full">{relatedArticle.category}</span>
                    <span className="text-xs text-muted-foreground">
                      {format(new Date(relatedArticle.publishedAt), isSwedish ? "d MMMM yyyy" : "MMMM d, yyyy", { locale: dateLocale })}
                    </span>
                  </div>
                  <h3 className="text-lg font-semibold group-hover:text-accent transition-colors line-clamp-2" style={{ color: '#0B1A33' }}>{relatedArticle.title}</h3>
                </div>
              </Link>
            ))}
          </div>
          <div className="text-center mt-10">
            <Link to={newsBase} className="btn-outline inline-flex items-center gap-2">
              {s.seeAllNews}
              <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        </Section>
      )}
    </Layout>
  );
};

export default NewsArticle;
