"use client";

import { useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../store";
import { formatDate } from "../../../../common/DateFormant";
import Image from "next/image";
import star2 from "../../../../assets/star.png";
import { truncateDescriptionListing } from "../../../../utils/commonFunction";
import { Listbox } from "@headlessui/react";
import { ChevronDownIcon } from "@heroicons/react/20/solid";

const sortOptions = [
  { value: "newest", label: "Newest first" },
  { value: "topRated", label: "Top Rated" },
];

function Review() {
  const reviewData = useSelector((state: RootState) => state.ViewSeller);
  const reviews = reviewData.data?.data?.allratings || [];

  const [currentPage, setCurrentPage] = useState(1);
  const [sortBy, setSortBy] = useState("newest");
  const reviewsPerPage = 5;

  // Sort logic
  const sortedReviews = [...reviews].sort((a, b) => {
    if (sortBy === "topRated") return b.rating - a.rating;
    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
  });

  // Pagination logic
  const indexOfLastReview = currentPage * reviewsPerPage;
  const indexOfFirstReview = indexOfLastReview - reviewsPerPage;
  const currentReviews = sortedReviews.slice(
    indexOfFirstReview,
    indexOfLastReview
  );
  const totalPages = Math.ceil(reviews.length / reviewsPerPage);

  // Star rendering
  const renderStars = (rating: number) => {
    return [...Array(5)].map((_, i) => (
      <Image
        unoptimized
        key={i}
        src={star2}
        alt="star"
        width={20}
        height={20}
        className={`inline-block ${
          i < rating ? "opacity-100" : "opacity-30 grayscale"
        }`}
      />
    ));
  };

  return (
    <div className="col-span-8 p-4 md:p-6  rounded-lg">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
        <div className="text-2xl sm:text-3xl font-bold text-gray-900">
          User Review
        </div>
        {reviews.length > 0 && (
          <Listbox
            value={sortBy}
            onChange={(value) => {
              setSortBy(value);
              setCurrentPage(1);
            }}
          >
            <div className="relative w-32 focus:outline-none">
              <Listbox.Button className="w-full bg-white border border-gray-200 rounded-md px-3 py-2 text-left shadow-2xl text-sm text-gray-700 focus:outline-none">
                {sortOptions.find((opt) => opt.value === sortBy)?.label}
              </Listbox.Button>
              <Listbox.Options className="absolute z-10 mt-1 w-full bg-white shadow-lg max-h-60 rounded-md py-1 text-sm ring-1 ring-black ring-opacity-5 overflow-auto">
                {sortOptions.map((option) => (
                  <Listbox.Option
                    key={option.value}
                    value={option.value}
                    className={({ selected }) =>
                      `cursor-pointer select-none relative px-4 py-2 ${
                        selected
                          ? "bg-[#04104E] text-white"
                          : "bg-white text-black"
                      }`
                    }
                  >
                    {option.label}
                  </Listbox.Option>
                ))}
              </Listbox.Options>
              <ChevronDownIcon className="pointer-events-none absolute right-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-black" />
            </div>
          </Listbox>
        )}
      </div>

      {/* Reviews List */}
      <div className="space-y-6">
        {reviews.length === 0 ? (
          <div className="text-center py-5">
            <div className="mx-auto h-20 w-20 text-gray-300 mb-4">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                className="w-full h-full"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1}
                  d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"
                />
              </svg>
            </div>
            <p className="text-gray-500 text-lg">No reviews yet</p>
            <p className="text-gray-500 text-lg">
              Your feedback helps sellers improve their products and services."
            </p>
          </div>
        ) : (
          currentReviews.map((review) => (
            <div
              key={review.id}
              className="flex flex-col sm:flex-row gap-6 p-5 bg-gray-50 rounded-lg border border-gray-200 hover:shadow-sm transition-shadow"
            >
              {/* Image & Buyer Info */}
              <div className="flex flex-col items-center sm:items-start gap-3 min-w-[150px]">
                <div className="relative w-[135px] h-[106px] rounded-lg overflow-hidden border border-gray-200">
                  <Image
                    unoptimized
                    src={
                      review.listing?.images?.[0] || "/placeholder-product.jpg"
                    }
                    alt="Listing Image"
                    fill
                    className="object-cover"
                    sizes="135px"
                  />
                </div>
                <div className="text-center sm:text-left">
                  <p className="text-gray-800 font-semibold">
                    {review.buyer?.name || "Anonymous"}
                  </p>
                  <p className="text-sm text-gray-500">
                    {formatDate(review.created_at)}
                  </p>
                </div>
              </div>

              {/* Review Content */}
              <div className="flex-1">
                <h3 className="text-lg font-bold text-gray-800 capitalize">
                  {review.listing?.product_name || "Product"}
                </h3>
                <div className="flex items-center gap-1 my-2">
                  {renderStars(review.rating)}
                  <span className="ml-1 text-sm text-gray-600">
                    {review.rating.toFixed(1)}
                  </span>
                </div>
                <p className="text-gray-700 mt-2 whitespace-pre-line">
                  {truncateDescriptionListing(
                    review.comment || "No comment provided"
                  )}
                </p>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Pagination */}
      {reviews.length > reviewsPerPage && (
        <div className="flex justify-center mt-8">
          <nav className="flex items-center gap-2">
            <button
              className={`px-3 py-1.5 rounded-md ${
                currentPage === 1
                  ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                  : "bg-blue-50 text-blue-600 hover:bg-blue-100"
              }`}
              onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              Previous
            </button>

            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum;
              if (totalPages <= 5) {
                pageNum = i + 1;
              } else if (currentPage <= 3) {
                pageNum = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i;
              } else {
                pageNum = currentPage - 2 + i;
              }

              return (
                <button
                  key={pageNum}
                  className={`px-3 py-1.5 rounded-md ${
                    currentPage === pageNum
                      ? "bg-blue-600 text-white"
                      : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                  }`}
                  onClick={() => setCurrentPage(pageNum)}
                >
                  {pageNum}
                </button>
              );
            })}

            <button
              className={`px-3 py-1.5 rounded-md ${
                currentPage === totalPages
                  ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                  : "bg-blue-50 text-blue-600 hover:bg-blue-100"
              }`}
              onClick={() =>
                setCurrentPage((prev) =>
                  indexOfLastReview >= reviews.length ? prev : prev + 1
                )
              }
              disabled={currentPage === totalPages}
            >
              Next
            </button>
          </nav>
        </div>
      )}
    </div>
  );
}

export default Review;
