"use client";

import { useState, useEffect } from "react";
import Head from "./Head";
import Title from "./title";
import LatestArticles from "./latestArticles";
import { request } from "@/services/response";
import { normalizeBlog } from "@/helper";

function BlogsPage() {
  const [blogs, setBlogs] = useState([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedTag, setSelectedTag] = useState(null);

  useEffect(() => {
    const fetchBlogs = async () => {
      try {
        setIsLoading(true);
        const params = {
          page: page,
          limit: 12,
        };
        if (selectedTag) {
          params.tag = selectedTag;
        }
        const response = await request.getBlogs(params);
        setBlogs((response?.data || []).map(normalizeBlog));
        setTotalPages(response?.meta?.totalPages || 1);
      } catch (error) {
        console.error("Error fetching blogs:", error);
        setBlogs([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchBlogs();
  }, [page, selectedTag]);

  const handlePageChange = (event, value) => {
    setPage(value);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const handleTagChange = (tagUuid) => {
    setSelectedTag(tagUuid);
    setPage(1);
  };

  return (
    <div className="padding-responsive pt-[84px] sm:pt-[110px] md:pt-[140px] lg:pt-[168px]">
      <Title onTagChange={handleTagChange} />
      <Head />
      <LatestArticles
        blogs={blogs}
        page={page}
        totalPages={totalPages}
        onPageChange={handlePageChange}
        isLoading={isLoading}
      />
    </div>
  );
}

export default BlogsPage;
