"use client";

import React, { useState } from "react";
import { BlogCard } from "@/components/blog/BlogCard";
import { BlogLoadMore } from "@/components/blog/BlogLoadMore";
import { BLOG_CATEGORIES, BlogBannerSearch, BlogCategoryTabs } from "@/components/blog/BlogHeaderFilter";
import { BlogSidebar } from "@/components/blog/BlogSidebar";
import type { BlogPost, OrderServiceConfig, PricingConfig } from "@/services/joomlaService";

import type { CalculatorConfig } from "@/types/home";

interface BlogMainContainerProps {
  initialPosts: BlogPost[];
  initialMostViewed: BlogPost[];
  mostViewedTotal: number;
  calculatorConfig: CalculatorConfig;
  orderConfig: OrderServiceConfig[];
  pricing: PricingConfig | null;
}

export const BlogMainContainer: React.FC<BlogMainContainerProps> = ({
  initialPosts,
  initialMostViewed,
  mostViewedTotal,
  calculatorConfig,
  orderConfig,
  pricing,
}) => {
  const [activeCategory, setActiveCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");

  const handleSelectCategory = (catId: string) => {
    setActiveCategory(catId);
    setSearchQuery("");
  };

  const handleSearch = (query: string) => {
    setSearchQuery(query);
    setActiveCategory("all");
  };

  // Filter posts based on search or category
  const filteredPosts = initialPosts.filter((post) => {
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      return (
        post.title.toLowerCase().includes(q) ||
        post.excerpt.toLowerCase().includes(q)
      );
    }
    return true;
  });

  const featuredPost = filteredPosts[0];
  // Maximum four dynamic blog cards in recent posts section
  const recentPosts = filteredPosts.slice(1, 5);

  const selectedCategoryLabel =
    BLOG_CATEGORIES.find((c) => c.id === activeCategory)?.label || "All Categories";

  return (
    <div className="min-h-[60vh] bg-white">
      {/* Banner Section (Green top strip) */}
      <section
        className="text-center px-4 sm:px-6 lg:px-8 pt-8 pb-8"
        style={{ background: "#688d3d" }}
      >
        <div className="max-w-4xl mx-auto space-y-2 mb-4">
          <h1 className="text-white text-2xl sm:text-4xl font-bold tracking-tight">
            Blog - Assignment Tips for University Students
          </h1>
          <p className="text-white/90 text-sm sm:text-base font-light">
            Blog posts to ease your concern
          </p>
        </div>

        {/* Search Bar inside green banner */}
        <BlogBannerSearch onSearch={handleSearch} />
      </section>

      {/* Category Tabs Bar OUTSIDE top strip, directly above featured story */}
      <BlogCategoryTabs
        activeCategory={activeCategory}
        onSelectCategory={handleSelectCategory}
      />

      {/* Main Content Area */}
      <div className="max-w-[1200px] mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {searchQuery && (
          <div className="mb-6 flex items-center justify-between bg-green-50 rounded-lg p-4 border border-green-200">
            <p className="text-sm font-medium text-slate-800">
              Showing search results for &ldquo;<span className="font-bold text-[#5C7A36]">{searchQuery}</span>&rdquo;
            </p>
            <button
              onClick={() => setSearchQuery("")}
              className="text-xs font-bold text-[#5C7A36] hover:underline"
            >
              Clear Search
            </button>
          </div>
        )}

        {filteredPosts.length === 0 ? (
          <div className="text-center py-16 rounded-xl border border-dashed border-slate-300 p-8">
            <p className="text-base font-semibold text-slate-700">No blog posts found.</p>
            <p className="text-sm text-slate-500 mt-1">
              Try searching with a different keyword or select another category.
            </p>
          </div>
        ) : (
          <div className="flex flex-col lg:flex-row justify-between gap-8 items-start">
            {/* Left Column (flex-1) */}
            <div className="w-full flex-1 min-w-0 space-y-8">
              {/* Featured Post / Latest Blog */}
              {featuredPost && (
                <div>
                  <h2 className="text-sm font-bold uppercase tracking-wider text-[#5C7A36] mb-3">
                    {activeCategory !== "all" ? selectedCategoryLabel : "Featured Story"}
                  </h2>
                  <BlogCard post={featuredPost} variant="featured" />
                </div>
              )}

              {/* Recent Posts (Maximum 4 dynamic blog cards) */}
              {recentPosts.length > 0 && (
                <div>
                  <h2 className="border-l-4 border-slate-700 pl-2.5 text-lg font-bold text-slate-800 mb-5">
                    Recent Posts
                  </h2>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    {recentPosts.slice(0, 4).map((post) => (
                      <BlogCard key={post.id} post={post} variant="recent" />
                    ))}
                  </div>
                </div>
              )}

              {/* Most Viewed Posts / Learn More Section */}
              {initialMostViewed.length > 0 && !searchQuery && (
                <div>
                  <h2 className="border-l-4 border-[#5C7A36] pl-2.5 text-lg font-bold text-slate-800 mb-5 flex items-center justify-between">
                    <span>Most Viewed</span>
                  </h2>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    {initialMostViewed.map((post) => (
                      <BlogCard key={post.id} post={post} variant="recent" />
                    ))}
                  </div>
                  {mostViewedTotal > initialMostViewed.length && (
                    <div className="mt-6">
                      <BlogLoadMore
                        initialOffset={initialMostViewed.length}
                        total={mostViewedTotal}
                        sort="hits"
                        buttonText="Load More Most Viewed"
                      />
                    </div>
                  )}
                </div>
              )}
            </div>


            {/* Right Sidebar (Exact 340px width matching live site) */}
            <div className="w-full lg:w-[340px] shrink-0">
              <BlogSidebar
                calculatorConfig={calculatorConfig}
                orderConfig={orderConfig}
                pricing={pricing}
              />
            </div>



          </div>
        )}
      </div>
    </div>
  );
};
