"use client";
import React, { useEffect, useState } from "react";
type ParentTab = "all" | "how to guides" | "pokemon" | "news";
import Image from "next/image";
import Link from "next/link";
import { fetchBlogs } from "../lib/api/blogs";

type BlogPost = {
  id: number;
  date: string; // e.g. "October 14, 2024"
  title: string;
  description: string;
  image?: string; // optional – cards without an image will show a dark block
};

const posts: BlogPost[] = [
  {
    id: 1,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 2,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 3,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 4,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 5,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 6,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 7,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
  {
    id: 8,
    date: "October 14, 2024",
    title:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    description:
      "Blog Title and heading and detail with some sugar, spice and everything nice",
    image: "/images/blogs/img.svg",
  },
];

type HistoryItem = {
  // ⚠️ adjust these to match your real API fields
  id: number | string;
  title: string; // e.g. "23-07-2025 12:45" or ISO string
  description: string; // "Deposit" / "Withdraw" etc.
};
type HistoryItems = {
  id: number | string;
  title: string; // e.g. "23-07-2025 12:45" or ISO string
  slug: string;
  content: string;
  image: string;
  created_at: null | string;
};
const pageSize = 7;

const Inner = () => {
  const [blogs, setBlogs] = useState<HistoryItems[]>([]);
  const [tabs, setTabs] = useState<ParentTab>("all");
  const [page, setPage] = useState(1);
  const [isLoadingBlogs, setIsLoadingBlogs] = useState(false);
  const totalPages = 999;
  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };

  const getBlogs = async (pageIndex: number) => {
    setIsLoadingBlogs(true);
    try {
      const res = await fetchBlogs(pageIndex);
      setBlogs(res);
      setIsLoadingBlogs(false);
    } catch (e: any) {
      console.log("error in getBlogs", e.message);
      setIsLoadingBlogs(false);
    }
  };

  const getImageUrl = (image?: string) => {
    if (!image) return "";

    // already full URL
    if (image.startsWith("http")) {
      return image;
    }

    // remove starting slash if exists
    const cleanPath = image.startsWith("/") ? image.slice(1) : image;

    return `https://openthatpack.com/${cleanPath}`;
  };

  useEffect(() => {
    getBlogs(page - 1);
  }, []);

  return (
    <div className="min-h-screen bg-black text-white">
      <div className=" z-10">
        <div className="container mx-auto py-4">
          <div className="flex gap-2 md:gap-4 my-3 2xl:my-6">
            <button
              onClick={() => {
                setTabs("all");
              }}
              className={`px-3 md:px-4 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl '
                  transition-all ${
                    tabs === "all"
                      ? "bg-(--color-blue) text-white "
                      : "text-(--color-slate) hover:bg-gray-700"
                  }`}
            >
              ALL
            </button>
            <button
              onClick={() => {
                setTabs("how to guides");
              }}
              className={`px-3 md:px-4 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl '
                  transition-all ${
                    tabs === "how to guides"
                      ? "bg-(--color-blue) text-white "
                      : "text-(--color-slate) hover:bg-(--color-gray)"
                  }`}
            >
              HOW TO GUIDES
            </button>
            <button
              onClick={() => {
                setTabs("pokemon");
              }}
              className={`px-3 md:px-4 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl '
                  transition-all ${
                    tabs === "pokemon"
                      ? "bg-(--color-blue) text-white "
                      : "text-(--color-slate) hover:bg-(--color-gray)"
                  }`}
            >
              POKEMON
            </button>
            <button
              onClick={() => {
                setTabs("news");
              }}
              className={`px-3 md:px-4 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl '
                  transition-all ${
                    tabs === "news"
                      ? "bg-(--color-blue) text-white "
                      : "text-(--color-slate) hover:bg-(--color-gray)"
                  }`}
            >
              NEWS
            </button>
          </div>
          <div className=" ">
            {isLoadingBlogs ? (
              <div className=" flex w-full h-65 items-center justify-center">
                <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
              </div>
            ) : (
              <>
                {/* Grid */}
                <div className="grid grid-cols-1 my-5 gap-5 sm:grid-cols-2 lg:grid-cols-4">
                  {blogs.map((post) => (
                    <Link
                      key={post.id}
                      href={`/blogs/${post.id}`}
                      className="block"
                    >
                      <article
                        key={post.id}
                        className="flex min-h-65 w-full mx-auto relative flex-col overflow-hidden  border border-slate-800 transition hover:border-slate-500/80"
                      >
                        {/* Date bar */}
                        <div className="absolute bg-[#29313D] z-20 text-white font-sofia top-0 px-3 md:px-5 py-1.5 text-[11px] font-semibold uppercase tracking-wide">
                          {post.title}
                        </div>

                        {/* Image / placeholder */}
                        <div className="relative  w-full overflow-hidden ">
                          {post.image ? (
                            <div className="relative aspect-4/3 w-full">
                              <Image
                                src={getImageUrl(post.image)}
                                alt={post.title}
                                fill
                                className="object-cover"
                              />
                            </div>
                          ) : (
                            <div className="aspect-4/3 w-full" />
                          )}
                        </div>

                        {/* Text content */}
                        <div className="flex font-onest flex-1 bg-blur blur-1 relative z-10 bg-[#12192499] -mt-7 flex-col gap-1 px-4 py-4">
                          <h3 className="line-clamp-3 text-sm font-semibold ">
                            {post.title}
                          </h3>
                          <p className="mt-1 line-clamp-3 text-xs text-[#54657E]">
                            {post.content}
                          </p>
                        </div>
                      </article>
                    </Link>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
        <div className="flex pb-4 md:pb-10 font-onest justify-center items-center gap-3 m-6">
          <button
            onClick={() => goToPage(page - 1)}
            disabled={page === 1}
            className="rounded-full w-8.5 h-8.5 flex justify-center items-center bg-(--color-gray) hover:bg-(--color-gray) disabled:opacity-40"
          >
            <img src="/images/profile/left.svg" alt="" />
          </button>

          {/* Page numbers */}
          <div className="flex gap-2 text-sm">
            {[...Array(totalPages)].map((_, i) => {
              const pg = i + 1;

              // show only first, last, current, and neighbors
              if (pg === 1 || pg === totalPages || Math.abs(pg - page) <= 1) {
                return (
                  <button
                    key={pg}
                    onClick={() => goToPage(pg)}
                    className={`px-3 py-1 rounded ${
                      pg === page
                        ? "scale-115 text-white"
                        : " text-(--color-naturalGray)"
                    }`}
                  >
                    {pg}
                  </button>
                );
              }

              // ellipsis
              if (pg === page - 2 || pg === page + 2) {
                return (
                  <span key={`ellipsis-${pg}`} className="px-2 text-gray-400">
                    ...
                  </span>
                );
              }

              return null;
            })}
          </div>

          <button
            onClick={() => goToPage(page + 1)}
            disabled={page === totalPages}
            className="flex justify-center items-center w-8.5 h-8.5 rounded-full bg-(--color-gray) hover:bg-(--color-gray) disabled:opacity-40"
          >
            <img src="/images/profile/right.svg" alt="" />
          </button>
        </div>
      </div>
    </div>
  );
};

export default Inner;
