"use client";

import * as React from "react";
import { useState, useEffect } from "react";
import { MediumCard } from "../../src/components/MediumCard";
import { BlogCommandBar } from "../../src/components/blog/BlogCommandBar";
import { blogPosts } from "../../src/data/blogPosts";
import { SectionHeader } from "../../src/components/SectionHeader";
import { Reveal } from "../../src/components/Reveal";
import { Section } from "../../src/components/Section";
import { AbstractCircuit, GradientMesh } from "../../src/components/Effects";
import { useAnalytics } from "../../src/components/analytics/useAnalytics";

export default function BlogPage() {
  const [searchQuery, setSearchQuery] = useState("");
  const [activeTags, setActiveTags] = useState<string[]>([]);
  const { trackEvent } = useAnalytics();

  // Memoize allPosts
  const allPosts = React.useMemo(
    () =>
      [...blogPosts].sort(
        (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime(),
      ),
    [],
  );

  const [filteredPosts, setFilteredPosts] = useState(allPosts);

  // Memoize allTags
  const allTags = React.useMemo(
    () => Array.from(new Set(allPosts.flatMap((post) => post.tags || []))),
    [allPosts],
  );

  const [visibleCount, setVisibleCount] = useState(8);

  const handleTagToggle = (tag: string) => {
    setActiveTags((prev) =>
      prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag],
    );
    setVisibleCount(8); // Reset pagination on filter change
  };

  useEffect(() => {
    const query = searchQuery.toLowerCase().trim();

    let filtered = allPosts;

    if (query) {
      filtered = filtered.filter((post) => {
        const title = post.title.toLowerCase();
        const description = post.description.toLowerCase();
        const pTagString = (post.tags || []).join(" ").toLowerCase();
        return (
          title.includes(query) ||
          description.includes(query) ||
          pTagString.includes(query)
        );
      });
    }

    if (activeTags.length > 0) {
      filtered = filtered.filter((post) =>
        post.tags?.some((tag) => activeTags.includes(tag)),
      );
    }

    setFilteredPosts(filtered);
  }, [searchQuery, activeTags, allPosts]);

  const loadMore = () => {
    setVisibleCount((prev) => prev + 6);
  };

  const hasMore = visibleCount < filteredPosts.length;
  const postsToShow = filteredPosts.slice(0, visibleCount);

  return (
    <div className="flex flex-col bg-slate-50/30 overflow-hidden relative min-h-screen">
      <AbstractCircuit />

      {/* Header Section */}
      <header className="relative pt-32 pb-8 md:pt-44 md:pb-12 z-20 overflow-hidden">
        <GradientMesh
          variant="metallic"
          className="opacity-20 absolute inset-0 -z-10"
        />
        <div className="narrow-container">
          <div className="space-y-4 text-center">
            <Reveal direction="down" delay={0.1}>
              <div className="flex items-center justify-center gap-4 text-[10px] font-bold uppercase tracking-[0.3em] text-slate-400">
                <div className="w-6 h-px bg-slate-200" />
                <span>Knowledge Base</span>
                <div className="w-12 h-px bg-slate-100" />
              </div>
            </Reveal>
            <Reveal delay={0.2}>
              <div className="flex flex-col items-center gap-6">
                <h1 className="text-5xl md:text-7xl font-bold text-slate-900 tracking-tighter leading-none">
                  Alle Artikel<span className="text-slate-300">.</span>
                </h1>
                <p className="font-serif italic text-slate-400 text-sm md:text-xl max-w-sm">
                  Gedanken über Engineering, Design und die Architektur der
                  Zukunft.
                </p>
              </div>
            </Reveal>
          </div>
        </div>
      </header>

      {/* Sticky Filter Bar */}
      <div className="sticky top-0 z-40 bg-slate-50/80 backdrop-blur-xl border-y border-slate-200/50 py-4 shadow-sm transition-all duration-300">
        <div className="narrow-container">
          <Reveal width="100%">
            <BlogCommandBar
              searchQuery={searchQuery}
              onSearchChange={setSearchQuery}
              tags={allTags}
              activeTags={activeTags}
              onTagToggle={handleTagToggle}
            />
          </Reveal>
        </div>
      </div>

      <Section
        className="pb-32 pt-12"
        containerVariant="narrow"
        variant="white"
      >
        <div className="space-y-12 relative z-10 p-4 md:p-0">
          {/* Posts List (Vertical & Minimal) */}
          <div id="posts-container" className="space-y-12">
            {postsToShow.length === 0 ? (
              <div className="py-24 text-center border border-dashed border-slate-200 rounded-3xl bg-white/50">
                <p className="text-slate-400 font-mono text-sm uppercase tracking-widest">
                  Keine Beiträge gefunden.
                </p>
                <button
                  onClick={() => {
                    setSearchQuery("");
                    setActiveTags([]);
                  }}
                  className="mt-4 text-xs font-bold text-slate-900 underline underline-offset-4 hover:text-slate-600"
                >
                  Filter zurücksetzen
                </button>
              </div>
            ) : (
              <div className="grid grid-cols-1 gap-6 w-full">
                {postsToShow.map((post, i) => (
                  <Reveal
                    key={post.slug}
                    delay={0.05 * i}
                    width="100%"
                    viewport={{ once: true, margin: "20% 0px" }} // Added more margin for better back-navigation detection
                  >
                    <MediumCard post={post} />
                  </Reveal>
                ))}
              </div>
            )}

            {/* Pagination */}
            {hasMore && (
              <div className="flex justify-center pt-8">
                <Reveal delay={0.1} width="fit-content">
                  <button
                    onClick={loadMore}
                    className="group relative px-8 py-4 bg-white border border-slate-200 text-slate-600 rounded-full overflow-hidden transition-all hover:border-slate-400 hover:text-slate-900 hover:shadow-lg"
                  >
                    <span className="relative z-10 font-mono text-xs uppercase tracking-widest flex items-center gap-3">
                      Mehr laden
                      <div className="w-1 h-1 bg-slate-300 rounded-full group-hover:bg-slate-900 transition-colors" />
                      <div className="w-1 h-1 bg-slate-300 rounded-full group-hover:bg-slate-900 transition-colors delay-75" />
                      <div className="w-1 h-1 bg-slate-300 rounded-full group-hover:bg-slate-900 transition-colors delay-150" />
                    </span>
                  </button>
                </Reveal>
              </div>
            )}
          </div>
        </div>
      </Section>
    </div>
  );
}
