"use client";

import { useState, useMemo } from "react";
import { BlogPost, BlogCategory, BLOG_CATEGORIES } from "@/content/blog";
import { BlogCard } from "./blog-card";
import { Search, ChevronLeft, ChevronRight, X, Mail, CheckCircle } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

interface BlogViewProps {
  posts: BlogPost[];
}

export function BlogView({ posts }: BlogViewProps) {
  const [selectedCategory, setSelectedCategory] = useState<BlogCategory>("All");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [subscribed, setSubscribed] = useState<boolean>(false);
  const [emailInput, setEmailInput] = useState<string>("");
  const [subscribeError, setSubscribeError] = useState<string | null>(null);
  const [subscribing, setSubscribing] = useState<boolean>(false);

  const POSTS_PER_PAGE = 6;

  // Filter posts based on category and search query
  const filteredPosts = useMemo(() => {
    return posts.filter((post) => {
      const matchesCategory =
        selectedCategory === "All" ? true : post.category === selectedCategory;

      const matchesSearch =
        searchQuery.trim() === "" ||
        post.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        post.excerpt.toLowerCase().includes(searchQuery.toLowerCase()) ||
        post.author.name.toLowerCase().includes(searchQuery.toLowerCase());

      return matchesCategory && matchesSearch;
    });
  }, [posts, selectedCategory, searchQuery]);

  // Paginated posts
  const totalPages = Math.ceil(filteredPosts.length / POSTS_PER_PAGE) || 1;
  const paginatedPosts = useMemo(() => {
    const startIndex = (currentPage - 1) * POSTS_PER_PAGE;
    return filteredPosts.slice(startIndex, startIndex + POSTS_PER_PAGE);
  }, [filteredPosts, currentPage]);

  const handleCategoryClick = (category: BlogCategory) => {
    setSelectedCategory(category);
    setCurrentPage(1);
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    setCurrentPage(1);
  };

  const clearSearch = () => {
    setSearchQuery("");
    setCurrentPage(1);
  };

  // Real submission to the newsletter API (which emails the sales inbox). Only
  // marks success after the server genuinely acknowledges — no fake success.
  const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault();
    const email = emailInput.trim();
    if (!email || !email.includes("@")) {
      setSubscribeError("Please enter a valid email address.");
      return;
    }
    setSubscribeError(null);
    setSubscribing(true);
    try {
      const res = await fetch("/api/newsletter", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const data = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string };
      if (!res.ok || !data.ok) {
        setSubscribeError(data.error || "Something went wrong. Please try again.");
        return;
      }
      setSubscribed(true);
      setEmailInput("");
    } catch {
      setSubscribeError("Couldn't reach the server. Please try again.");
    } finally {
      setSubscribing(false);
    }
  };

  return (
    <section className="mt-16 sm:mt-24" id="all-blogs">
      {/* Section Title */}
      <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-5 border-b border-border/60 pb-6">
        <div>
          <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight text-foreground">
            All Blogs
          </h2>
          <p className="mt-2 text-sm text-muted-foreground">
            Engineering playbooks, compliance architectures, and enterprise voice automation benchmarks.
          </p>
        </div>

        {/* Search Bar */}
        <div className="relative w-full max-w-xs">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
          <Input
            type="text"
            aria-label="Search articles"
            placeholder="Search all articles..."
            value={searchQuery}
            onChange={handleSearchChange}
            className="pl-9 pr-9 text-xs rounded-full border-border/80 bg-background focus-visible:ring-1 focus-visible:ring-ring"
          />
          {searchQuery && (
            <button
              onClick={clearSearch}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              aria-label="Clear search"
            >
              <X className="size-3.5" />
            </button>
          )}
        </div>
      </div>

      {/* Category Pills Bar — horizontal swipe strip on mobile, wraps on sm+ */}
      <div className="mt-8 flex snap-x flex-nowrap items-center gap-2.5 overflow-x-auto pb-2 scrollbar-none [-webkit-overflow-scrolling:touch] sm:flex-wrap sm:overflow-visible">
        {BLOG_CATEGORIES.map((category) => {
          const isActive = selectedCategory === category;
          return (
            <button
              key={category}
              onClick={() => handleCategoryClick(category)}
              aria-pressed={isActive}
              className={`shrink-0 snap-start rounded-full px-4 py-2 text-xs font-bold uppercase tracking-wider transition-all duration-200 whitespace-nowrap ${
                isActive
                  ? "bg-gradient-brand text-white font-bold shadow-xs glow-brand ring-0"
                  : "border border-border/80 bg-card text-muted-foreground hover:border-[#4FDAF1]/40 hover:text-foreground"
              }`}
            >
              {category}
            </button>
          );
        })}
      </div>

      {/* 3-Column Bento Articles Grid */}
      {paginatedPosts.length > 0 ? (
        <div className="mt-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {paginatedPosts.map((post) => (
            <BlogCard key={post.slug} post={post} />
          ))}
        </div>
      ) : (
        <div className="mt-12 flex flex-col items-center justify-center rounded-2xl border border-dashed border-border p-12 text-center">
          <p className="text-base font-semibold text-foreground">
            No articles found matching &quot;{searchQuery}&quot;
          </p>
          <p className="mt-1 text-sm text-muted-foreground">
            Try searching for other terms like &ldquo;security&rdquo;, &ldquo;HIPAA&rdquo;, &ldquo;Shopify&rdquo; or reset filters.
          </p>
          <Button
            onClick={() => {
              setSelectedCategory("All");
              setSearchQuery("");
            }}
            variant="outline"
            size="sm"
            className="mt-4 rounded-full"
          >
            Reset Filters
          </Button>
        </div>
      )}

      {/* Pagination Bar */}
      {totalPages > 1 && (
        <div className="mt-12 flex flex-wrap items-center justify-center gap-2">
          <button
            onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
            disabled={currentPage === 1}
            aria-label="Previous page"
            className="flex size-9 items-center justify-center rounded-full border border-border/80 bg-card text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground disabled:opacity-40 disabled:pointer-events-none"
          >
            <ChevronLeft className="size-4" />
          </button>

          {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
            <button
              key={page}
              onClick={() => setCurrentPage(page)}
              aria-current={currentPage === page ? "page" : undefined}
              className={`flex size-9 items-center justify-center rounded-full text-xs font-bold transition-all ${
                currentPage === page
                  ? "bg-foreground text-background shadow-xs"
                  : "border border-border/70 bg-card text-muted-foreground hover:border-foreground/40 hover:text-foreground"
              }`}
            >
              {page}
            </button>
          ))}

          <button
            onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
            disabled={currentPage === totalPages}
            aria-label="Next page"
            className="flex size-9 items-center justify-center rounded-full border border-border/80 bg-card text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground disabled:opacity-40 disabled:pointer-events-none"
          >
            <ChevronRight className="size-4" />
          </button>
        </div>
      )}

      {/* Integrated Newsletter Subscription Banner */}
      <div className="mt-18 overflow-hidden rounded-3xl border border-border/80 bg-card p-7 sm:p-10 shadow-sm text-center md:text-left">
        <div className="flex flex-col md:flex-row items-center justify-between gap-6">
          <div className="max-w-md space-y-2">
            <span className="rounded-full border border-[var(--accent-cyan-text)]/30 bg-[var(--accent-cyan-text)]/10 px-3 py-1 text-[11px] font-bold text-[var(--accent-cyan-text)] uppercase tracking-wider">
              Voice AI Intelligence
            </span>
            <h3 className="text-xl sm:text-2xl font-extrabold tracking-tight text-foreground">
              Subscribe to <span className="text-gradient-brand">Quto Voice Dispatch</span>
            </h3>
            <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
              Bi-weekly technical teardowns on sub-500ms voice pipelines, compliance mandates, and conversion benchmarks.
            </p>
          </div>

          <div className="w-full max-w-md">
            {subscribed ? (
              <div role="status" className="flex items-center justify-center md:justify-start gap-2 text-sm font-semibold text-foreground">
                <CheckCircle className="size-5 text-[var(--accent-cyan-text)]" />
                <span>You&apos;re subscribed! Check your inbox for our 2026 voice benchmarks.</span>
              </div>
            ) : (
              <form onSubmit={handleSubscribe} className="flex flex-col sm:flex-row gap-2.5" noValidate>
                <div className="relative flex-1">
                  <Mail className="absolute left-3.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
                  <Input
                    type="email"
                    required
                    aria-label="Work email"
                    placeholder="Enter your work email"
                    value={emailInput}
                    onChange={(e) => setEmailInput(e.target.value)}
                    className="pl-9 text-xs rounded-full border-border bg-background"
                  />
                </div>
                <Button
                  type="submit"
                  variant="accent"
                  size="sm"
                  loading={subscribing}
                  className="rounded-full font-bold px-6 shadow-xs"
                >
                  {subscribing ? "Subscribing…" : "Subscribe"}
                </Button>
              </form>
            )}
            {subscribeError && !subscribed && (
              <p role="alert" className="mt-2 text-xs font-medium text-destructive">
                {subscribeError}
              </p>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
