"use client";

import { useAuth } from "@/lib/context/auth-context";
import { ReviewItem, ReviewItemData } from "@/lib/types/models/review";
import ReviewModal from "@/modules/common/review-modal";
import StarRating from "@/modules/ui/star-rating";
import Link from "next/link";
import React, { useCallback, useState } from "react";

export default function Page({
  reviewData,
  productId,
}: {
  reviewData: ReviewItemData;
  productId: string;
}) {
  const { userToken } = useAuth();
  const [isModalOpen, setIsModalOpen] = useState(false);

  const averageRating = Number(reviewData?.average);
  const totalReviews = reviewData?.count || 0;
  const reviews = reviewData?.reviews || [];
  const ratingsPercentage = reviewData?.ratingsPercentage || {};

  const handleOpenModal = useCallback(() => setIsModalOpen(true), []);
  const handleCloseModal = useCallback(() => setIsModalOpen(false), []);

  return (
    <>
      <h2 className="text-2xl lg:text-3xl font-semibold text-neutral-black-87 mb-5 lg:mb-8">
        Customer Reviews
      </h2>
      <div className="flex flex-col lg:flex-row lg:gap-8">
        <div className="w-full lg:w-1/3">
          <div className="flex items-center">
            <StarRating fillRating={averageRating} />
            <p className="ms-1 text-sm font-medium text-neutral-black-87">
              {averageRating?.toFixed(0)} out of 5
            </p>
          </div>
          <p className="text-md font-medium text-neutral-black-87 my-2">
            {totalReviews} Reviews
          </p>

          {[5, 4, 3, 2, 1].map((stars) => (
            <div key={stars} className="flex items-center mt-4">
              <div className="text-neutral-black-54 text-md font-medium flex items-center gap-1 min-w-[2rem]">
                {stars}
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  width={20}
                  height={20}
                >
                  <path
                    fill="#facc15"
                    d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.5l-6.18 3.22L7 14.14l-5-4.87 6.91-1.01L12 2z"
                  />
                </svg>
              </div>
              <div className="w-full lg:w-2/4 h-3 mx-4 bg-gray-200 rounded-full">
                <div
                  className="h-3 bg-yellow-400 rounded-full"
                  style={{ width: `${ratingsPercentage[stars] || 0}%` }}
                ></div>
              </div>
              <span className="text-md font-medium min-w-[3rem] text-neutral-black-54">
                {ratingsPercentage[stars]}%
              </span>
            </div>
          ))}

          {/* Call to Action */}
          <h3 className="text-xl lg:text-2xl font-medium text-neutral-black-87 mt-10">
            Share your thoughts
          </h3>
          {userToken ? (
            <>
              <div className="lg:w-2/3 text-md mt-2 text-gray-500">
                If you’ve used this product, share your thoughts with other
                customers
              </div>
              <button
                type="button"
                className="w-full lg:w-8/12 my-8 text-gray-900 bg-white border border-gray-300 focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-100 font-medium rounded-lg text-md px-5 py-2.5 transition-colors"
                onClick={() => handleOpenModal()}
              >
                Write a review
              </button>
            </>
          ) : (
            <>
              <div className="lg:w-2/3 text-md mt-2 text-gray-500">
                You must login to write a review.
              </div>
              <Link href={"/login"}>
                <button
                  type="button"
                  className="w-full lg:w-8/12 my-8 text-gray-900 bg-white border border-gray-300 focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-100 font-medium rounded-lg text-md px-5 py-2.5 transition-colors"
                >
                  Go to Login
                </button>
              </Link>
            </>
          )}
        </div>

        {/* Reviews List */}
        <div className="w-full lg:w-2/3">
          {reviews.length === 0 ? (
            <p>No reviews yet...</p>
          ) : (
            reviews.map((review: ReviewItem) => (
              <article
                key={review._id}
                className="py-4 border-b border-gray-200"
              >
                <StarRating fillRating={review?.rating} />
                <div className="font-medium text-sm text-gray-500 py-2">
                  {new Date(review?.createdAt)?.toLocaleDateString()} by{" "}
                  {review.userId?.FirstName} {review.userId?.LastName}
                </div>
                <h3 className="text-lg font-semibold text-neutral-black-87">
                  {review?.review}
                </h3>
              </article>
            ))
          )}
        </div>
      </div>
      <ReviewModal
        productId={productId}
        isModalOpen={isModalOpen}
        setIsModalOpen={() => handleCloseModal()}
      />
    </>
  );
}
