import { useState } from "react";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useForceLanguage } from "@/hooks/useForceLanguage";
import { Layout } from "@/components/layout/Layout";
import { Section } from "@/components/ui/Section";
import { SEO } from "@/components/SEO";
import { useArticles, NewsArticle } from "@/hooks/useArticles";
import { newsStrings, newsBasePathFor, NewsLang } from "@/lib/newsStrings";
import { format } from "date-fns";
import { sv, enUS } from "date-fns/locale";
import { ArrowRight } from "lucide-react";
import newsHeroBg from "@/assets/news/news-hero-bg.jpg";

type CategoryFilter = "all" | NewsArticle["category"];

const CATEGORIES: { key: CategoryFilter; label: string }[] = [
  { key: "all", label: "all" },
  { key: "VR", label: "VR Training" },
  { key: "Hologram", label: "Hologram" },
  { key: "AI", label: "AI Solutions" },
];

interface NewsProps { lang?: NewsLang; seoOverride?: React.ReactNode; }

const News = ({ lang = "sv", seoOverride }: NewsProps) => {
  const { t } = useTranslation();
  useForceLanguage(lang);
  const [filter, setFilter] = useState<CategoryFilter>("all");
  const isSwedish = lang === "sv";
  const s = newsStrings[lang];
  const newsBase = newsBasePathFor(lang);
  const dateLocale = isSwedish ? sv : enUS;
  const { data: articles = [], isLoading, isError } = useArticles(lang);
  const filteredArticles = filter === "all" ? articles : articles.filter(a => a.category === filter);

  const featured = filteredArticles[0];
  const rest = filteredArticles.slice(1);

  return (
    <Layout>
      {seoOverride || (
        <SEO
          title="Nyheter och insikter | Suteki Studios"
          description="Senaste nytt om hologram, VR och AI från Suteki Studios. Branschnyheter, produktlanseringar och kundberättelser."
          lang="sv"
          canonicalUrl="https://sutekistudios.com/nyheter"
          alternateSv="https://sutekistudios.com/nyheter"
          alternateEn="https://sutekistudios.com/en/news"
        />
      )}

      {/* Hero */}
      <section className="min-h-[65vh] flex items-end relative overflow-hidden" data-hero="true">
        <div className="absolute inset-0 bg-cover bg-center" style={{ backgroundImage: `url(${newsHeroBg})` }} />
        <div className="absolute inset-0" style={{ background: 'linear-gradient(to top, rgba(8,12,20,0.92) 0%, rgba(8,12,20,0.45) 50%, rgba(8,12,20,0.18) 100%)' }} />
        <div className="container mx-auto px-6 lg:px-8 relative z-10 pb-20 pt-40">
          <div className="max-w-2xl">
            <p className="hero-eyebrow mb-5 animate-fade-up">{t("news.eyebrow", { defaultValue: "Insights" })}</p>
            <h1 className="display mb-5 hero-text-white animate-fade-up">{t("news.title")}</h1>
            <p className="text-lg hero-text-body animate-fade-up-delay-1">{t("news.subtitle")}</p>
          </div>
        </div>
      </section>

      {/* Category Filters */}
      <section className="section-white border-b border-border">
        <div className="container mx-auto px-6 lg:px-8 py-5">
          <div className="flex flex-wrap gap-2 items-center">
            <span className="text-muted-foreground text-sm mr-2">{s.filter}</span>
            {CATEGORIES.map(({ key, label }) => (
              <button key={key} onClick={() => setFilter(key)}
                className={`px-5 py-2 rounded-full text-sm font-medium transition-colors duration-200 ${
                  filter === key
                    ? "bg-foreground text-background"
                    : "bg-transparent text-muted-foreground border border-border hover:border-foreground/30"
                }`}
              >
                {key === "all" ? s.all : label}
              </button>
            ))}
          </div>
        </div>
      </section>

      {isError && (
        <Section className="section-white">
          <div className="text-red-600 p-8 text-center">
            <p className="font-bold">{s.error}</p>
          </div>
        </Section>
      )}

      {isLoading && (
        <Section className="section-white">
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
            {[1,2,3].map(i => (
              <div key={i} className="enterprise-card overflow-hidden animate-pulse">
                <div className="aspect-[16/10] bg-muted" />
                <div className="p-6 space-y-3">
                  <div className="h-4 bg-muted rounded w-1/3" />
                  <div className="h-5 bg-muted rounded w-2/3" />
                  <div className="h-4 bg-muted rounded w-full" />
                </div>
              </div>
            ))}
          </div>
        </Section>
      )}

      {!isLoading && !isError && articles.length === 0 && (
        <Section className="section-white">
          <p className="text-center text-muted-foreground py-12">{s.empty}</p>
        </Section>
      )}

      {/* Featured Story */}
      {featured && (
        <Section className="section-beige">
          <Link to={`${newsBase}/${featured.slug}`} className="group grid lg:grid-cols-2 gap-0 enterprise-card overflow-hidden">
            <div className="aspect-[4/3] lg:aspect-auto lg:min-h-[440px] overflow-hidden">
              <img src={featured.heroImage} alt={featured.title}
                className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
            </div>
            <div className="p-8 lg:p-12 flex flex-col justify-center">
              <div className="flex items-center gap-3 mb-5">
                <span className="px-2.5 py-0.5 text-[11px] font-medium bg-secondary text-secondary-foreground rounded-full">{featured.category}</span>
                <span className="text-xs text-muted-foreground">
                  {format(new Date(featured.publishedAt), isSwedish ? "d MMMM yyyy" : "MMMM d, yyyy", { locale: dateLocale })}
                </span>
              </div>
              <h2 className="text-2xl lg:text-3xl font-semibold mb-4 group-hover:text-accent transition-colors text-foreground leading-tight">{featured.title}</h2>
              <p className="text-muted-foreground leading-relaxed mb-8 line-clamp-2" style={{ color: 'rgba(11,26,51,0.85)' }}>{featured.excerpt}</p>
              <div className="flex items-center text-sm font-medium text-accent group-hover:underline underline-offset-4">
                {s.readMore}
                <ArrowRight className="ml-1.5 h-3.5 w-3.5 transition-transform group-hover:translate-x-1" />
              </div>
            </div>
          </Link>
        </Section>
      )}

      {/* Article Grid */}
      {rest.length > 0 && (
        <Section className="section-white">
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
            {rest.map((article) => (
              <Link key={article.id} to={`${newsBase}/${article.slug}`}
                className="group enterprise-card overflow-hidden flex flex-col"
              >
                <div className="aspect-[16/10] overflow-hidden">
                  <img src={article.heroImage} alt={article.title}
                    className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" loading="lazy" />
                </div>
                <div className="p-6 flex flex-col flex-1">
                  <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">{article.category}</span>
                    <span className="text-xs text-muted-foreground">
                      {format(new Date(article.publishedAt), isSwedish ? "d MMMM yyyy" : "MMMM d, yyyy", { locale: dateLocale })}
                    </span>
                  </div>
                  <h2 className="text-lg font-semibold mb-3 group-hover:text-accent transition-colors duration-300 line-clamp-2" style={{ color: '#0B1A33' }}>{article.title}</h2>
                  <p className="line-clamp-2 text-[15px] leading-relaxed flex-1" style={{ color: 'rgba(11,26,51,0.85)' }}>{article.excerpt}</p>
                  <div className="mt-5 text-accent font-medium text-sm inline-flex items-center gap-1 group-hover:underline underline-offset-4">
                    {s.readMore}
                    <ArrowRight className="h-3.5 w-3.5" />
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </Section>
      )}
    </Layout>
  );
};

export default News;
