"use client";

import { useState, useMemo, useRef, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import BlueArrow from "../../../../public/images/blue-arrow.svg";
import SearchIcon from "../../../../public/images/search-icon.svg";
import { BlogBannerWithProps } from "@/types/blogs";
import BlogsSkeleton from "@/components/Blogs/BlogsSkeleton";

// Tracks if this is the first paint of the client bundle.
// Hydration must match the server HTML (which contains posts for SEO),
// while client-side routes transition triggers the skeleton.
let isFirstLoad = true;

export default function BlogBannerWithPost({ heading, description, blog_cards }: BlogBannerWithProps) {
    const searchParams = useSearchParams();
    const [searchQuery, setSearchQuery] = useState("");
    const [currentPage, setCurrentPage] = useState(1);
    const sectionRef = useRef<HTMLDivElement>(null);
    const [loading, setLoading] = useState(!isFirstLoad);

    useEffect(() => {
        if (loading) {
            const timer = setTimeout(() => {
                setLoading(false);
            }, 600); // 600ms transition time
            return () => clearTimeout(timer);
        }
        isFirstLoad = false;
    }, [loading]);

    useEffect(() => {
        const query = searchParams.get("search");
        if (query) {
            setSearchQuery(query);
            setCurrentPage(1);
        } else {
            setSearchQuery("");
        }
    }, [searchParams]);

    const filteredPosts = useMemo(() => {
        const query = searchQuery.toLowerCase().trim();
        if (!query) return blog_cards ?? [];
        return (blog_cards ?? []).filter(card =>
            card.title.toLowerCase().includes(query)
        );
    }, [blog_cards, searchQuery]);

    const postsPerPage = 9;
    const totalPages = Math.ceil(filteredPosts.length / postsPerPage);
    const activePage = currentPage > totalPages ? 1 : currentPage;

    const paginatedPosts = useMemo(() => {
        const startIndex = (activePage - 1) * postsPerPage;
        return filteredPosts.slice(startIndex, startIndex + postsPerPage);
    }, [filteredPosts, activePage]);

    const handlePageChange = (page: number) => {
        setCurrentPage(page);
        if (sectionRef.current) {
            const yOffset = -100;
            const y = sectionRef.current.getBoundingClientRect().top + window.scrollY + yOffset;
            window.scrollTo({ top: y, behavior: "smooth" });
        }
    };

    if (loading) {
        return <BlogsSkeleton />;
    }

    return (
        <section ref={sectionRef} className="mb-16 md:mb-30">
            <div className="container">
                {/* Heading and description */}
                <div className="max-w-[846px] mx-auto md:text-center my-10 md:my-20">
                    <h2 className="text-[32px] md:text-[40px] xl:text-[48px] text-[#00204F] font-medium leading-[1.1] max-w-[700px] mx-auto mb-3 md:mb-5">
                        {heading}
                    </h2>
                    <p className="text-[18px] md:text-[20px] text-[#334D72] font-normal leading-[1.3]">
                        {description}
                    </p>
                </div>

                {/* Search bar */}
                <div className="flex items-center gap-2 w-full lg:max-w-[400px] mx-auto mb-10 rounded-full border border-[rgba(24,30,59,0.6)] px-[16px] py-[14px] bg-white focus-within:border-[#1718FF] transition-colors">
                    <Image src={SearchIcon} width={20} height={20} alt="Search" />
                    <input
                        type="text"
                        placeholder="Search"
                        value={searchQuery}
                        onChange={(e) => {
                            setSearchQuery(e.target.value);
                            setCurrentPage(1);
                        }}
                        className="w-full outline-none placeholder:text-[16px] placeholder:text-[#334D72] text-[#00204F]"
                    />
                    {searchQuery && (
                        <button
                            onClick={() => {
                                setSearchQuery("");
                                setCurrentPage(1);
                            }}
                            className="text-[#667995] hover:text-[#1718FF] transition-colors cursor-pointer mr-1"
                            aria-label="Clear search"
                        >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                            </svg>
                        </button>
                    )}
                </div>

                {filteredPosts.length === 0 ? (
                    <div className="text-center py-16 px-4 bg-[#F8FAFC] rounded-[24px] border border-dashed border-[#CCD2DC] max-w-[500px] mx-auto mt-6">
                        <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#EEF2FF] text-[#1718FF] mb-4">
                            <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.637 10.637Z" />
                            </svg>
                        </div>
                        <h4 className="text-[20px] text-[#00204F] font-bold mb-2">No results found</h4>
                        <p className="text-[16px] text-[#334D72] leading-relaxed mb-5">
                            We couldn&apos;t find any articles matching &ldquo;{searchQuery}&rdquo;. Try checking the spelling or searching for another keyword.
                        </p>
                        <button
                            onClick={() => {
                                setSearchQuery("");
                                setCurrentPage(1);
                            }}
                            className="inline-flex items-center justify-center px-5 py-2.5 rounded-[8px] bg-[#1718FF] hover:bg-[#0004ff] text-white font-bold text-[15px] transition-all cursor-pointer shadow-md hover:shadow-lg"
                        >
                            Clear Search
                        </button>
                    </div>
                ) : (
                    <>
                        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-x-5 gap-y-8 md:gap-y-16 xl:gap-y-20">
                            {paginatedPosts.map((card) => (
                                <div key={card.id} className="flex flex-col h-full">
                                    <figure className="overflow-hidden rounded-[16px] w-full h-[185px] md:h-[250px] relative">
                                        <Image
                                            className="rounded-[16px] transition-transform duration-500 hover:scale-105 object-cover"
                                            src={card.featured_image}
                                            alt={card.title}
                                            fill
                                            sizes="(max-width: 768px) 100vw, (max-width: 1280px) 50vw, 33vw"
                                        />
                                    </figure>
                                    <span className="text-[14px] text-[#667995] font-medium uppercase inline-block mt-6 mb-2">
                                        {card.published_date}
                                    </span>
                                    <h6 className="text-[20px] md:text-[24px] text-[#00204F] font-bold tracking-normal leading-[1.3] mb-4 md:mb-6 line-clamp-2">
                                        <Link href={`/blogs/${card.slug}`}>
                                            {card.title}
                                        </Link>
                                    </h6>
                                    <Link href={`/blogs/${card.slug}`} className="flex items-center mt-auto">
                                        <span className="text-[16px] text-[#1718FF] font-bold mr-1 inline-block">
                                            {card.button_text}
                                        </span>
                                        <Image src={BlueArrow} width={16} height={16} alt="blue-arrow" />
                                    </Link>
                                </div>
                            ))}
                        </div>

                        {totalPages > 1 && (
                            <div className="flex items-center justify-center gap-2 mt-16 md:mt-20">
                                <button
                                    onClick={() => handlePageChange(activePage - 1)}
                                    disabled={activePage === 1}
                                    className="flex items-center justify-center w-10 h-10 rounded-full border border-[#CCD2DC] text-[#334D72] hover:text-[#1718FF] hover:border-[#1718FF] disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:text-[#334D72] disabled:hover:border-[#CCD2DC] transition-all cursor-pointer bg-white"
                                    aria-label="Previous Page"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
                                    </svg>
                                </button>

                                {Array.from({ length: totalPages }).map((_, i) => {
                                    const pageNum = i + 1;
                                    const isActive = pageNum === activePage;
                                    return (
                                        <button
                                            key={pageNum}
                                            onClick={() => handlePageChange(pageNum)}
                                            className={`flex items-center justify-center w-8 h-8 md:w-10 md:h-10 rounded-full text-[14px] md:text-[16px] font-bold transition-all cursor-pointer ${isActive
                                                ? "bg-[#1718FF] text-white"
                                                : "text-[#334D72] bg-white hover:bg-[#EEF2FF] hover:text-[#1718FF] border border-transparent hover:border-[#EEF2FF]"
                                                }`}
                                        >
                                            {pageNum}
                                        </button>
                                    );
                                })}

                                <button
                                    onClick={() => handlePageChange(activePage + 1)}
                                    disabled={activePage === totalPages}
                                    className="flex items-center justify-center w-8 h-8 md:w-10 md:h-10 rounded-full border border-[#CCD2DC] text-[#334D72] hover:text-[#1718FF] hover:border-[#1718FF] disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:text-[#334D72] disabled:hover:border-[#CCD2DC] transition-all cursor-pointer bg-white"
                                    aria-label="Next Page"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                                    </svg>
                                </button>
                            </div>
                        )}
                    </>
                )}
            </div>
        </section>
    );
}