import React, { useEffect, useState } from "react";
import "./Customer_Feedbacks.css";
import Customer_Feedbacks_cards from "./customer_Feedbacks_cards/Customer_Feedbacks_cards";
import { formatDateTime } from "../../../../utils/common";
import { useDispatch, useSelector } from "react-redux";
import { allReviewRating } from "../../../../features/review_rating/review_ratingSlice";

function Customer_Feedbacks({ product }) {
  // const itemsPerPage = all_rating?.per_page;
  const [currentPage, setCurrentPage] = useState(1);
  // const totalPages = Math.ceil(all_rating?.total_pages);

  const dispatch = useDispatch();

  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  const all_rating = useSelector((state) => state.reviewRating.all_rating);

  useEffect(() => {
    dispatch(
      allReviewRating({
        product_id: product.id,
        page: currentPage,
      }),
    );
  }, [dispatch, product, currentPage]);

  const itemsPerPage = all_rating?.per_page || 3;
  // const itemsPerPage = 3;
  const totalItems = all_rating?.total || all_rating?.data?.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);

  const getVisiblePages = () => {
    const visiblePages = [];

    // Always show 1 and last page
    if (totalPages <= 3) {
      for (let i = 1; i <= totalPages; i++) visiblePages.push(i);
    } else {
      visiblePages.push(1);

      if (currentPage > 2) visiblePages.push(currentPage - 1);
      if (currentPage !== 1 && currentPage !== totalPages)
        visiblePages.push(currentPage);
      if (currentPage < totalPages - 1) visiblePages.push(currentPage + 1);

      visiblePages.push(totalPages);
    }

    return [...new Set(visiblePages)].sort((a, b) => a - b); // remove duplicates and sort
  };

  return (
    <div>
      <section className="Customer_Feedbacks">
        <div className="heading_holder">
          <h4>Customer Feedbacks</h4>
        </div>

        <div className="Customer_Feedbacks_cards_holder row">
          {all_rating?.data?.map((feedback, index) => (
            <div key={index}>
              <Customer_Feedbacks_cards
                // nameText={feedback?.User?.name}
                nameText={feedback?.User?.name || feedback?.name}
                rating={feedback?.ratings}
                // imgSrc={feedback.}
                dateText={formatDateTime(feedback.createdAt)}
                productName={feedback?.Product?.name}
                boldText={feedback?.review}
                images={feedback?.Rating_Images}
              />
            </div>
          ))}
        </div>

        {/* Pagination UI */}
        <div className="pagination pagination_holder mt-4 d-flex justify-content-center align-items-center gap-2">
          <button
            onClick={() => handlePageChange(1)}
            disabled={currentPage === 1}
          >
            &laquo;
          </button>
          <button
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            &lsaquo;
          </button>

          {getVisiblePages().map((page, idx, arr) => (
            <>
              {/* Show dots between jumps */}
              {idx > 0 && page - arr[idx - 1] > 1 && (
                <span key={`dot-${idx}`}>...</span>
              )}
              <button
                key={page}
                onClick={() => handlePageChange(page)}
                className={page === currentPage ? "active" : ""}
              >
                {page}
              </button>
            </>
          ))}

          <button
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            &rsaquo;
          </button>
          <button
            onClick={() => handlePageChange(totalPages)}
            disabled={currentPage === totalPages}
          >
            &raquo;
          </button>
        </div>
      </section>
    </div>
  );
}

export default Customer_Feedbacks;
