"use client";

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../store";
import { reviewsHistory } from "../../../api/api";
import Image from "next/image";
import { truncateDescriptionListing } from "../../../utils/commonFunction";

// Star rating component
const StarRating = ({ rating }: { rating: number }) => (
  <div className="flex items-center mb-3">
    {[...Array(5)].map((_, index) => (
      <svg
        key={index}
        className={`w-5 h-5 ${
          index < rating ? "text-yellow-400" : "text-gray-200"
        }`}
        fill="currentColor"
        viewBox="0 0 20 20"
      >
        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.286 3.973a1 1 0 00.95.69h4.186c.969 0 1.371 1.24.588 1.81l-3.39 2.46a1 1 0 00-.364 1.118l1.286 3.973c.3.921-.755 1.688-1.54 1.118l-3.39-2.46a1 1 0 00-1.175 0l-3.39 2.46c-.784.57-1.838-.197-1.539-1.118l1.286-3.973a1 1 0 00-.364-1.118L2.048 9.4c-.783-.57-.38-1.81.588-1.81h4.186a1 1 0 00.95-.69l1.286-3.973z" />
      </svg>
    ))}
  </div>
);

// Empty state component
const EmptyState = ({
  title,
  subtitle,
  icon,
}: {
  title: string;
  subtitle: string;
  buttonText: string;
  icon: React.ReactNode;
}) => (
  <div className="text-center py-12">
    <div className="mx-auto h-20 w-20 text-gray-300 mb-4">{icon}</div>
    <h3 className="text-lg font-medium text-gray-900 mb-2">{title}</h3>
    <p className="text-gray-500 max-w-md mx-auto mb-6">{subtitle}</p>
  </div>
);

function Page() {
  const [activeTab, setActiveTab] = useState<"given" | "my">("given");
  const dispatch = useDispatch<any>();
  const { reviewHistoryData } = useSelector(
    (state: RootState) => state.ReviewReducer
  );

  useEffect(() => {
    dispatch(reviewsHistory());
  }, [dispatch]);

  const givenReviews = reviewHistoryData?.data?.given_review || [];
  const receivedReviews = reviewHistoryData?.data?.received_review || [];

  return (
    <div className="container mx-auto px-4 sm:px-6 py-8 max-w-7xl">
      {/* Header */}
      <div className="flex flex-col mb-8">
        <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">
          Your Reviews
        </h1>
      </div>

      {/* Tabs */}
      <div className="flex space-x-2 mb-6 sm:mb-8">
        {["given", "my"].map((tab) => (
          <button
            key={tab}
            className={`px-4 py-2 rounded-full font-medium text-xs sm:text-sm transition-colors ${
              activeTab === tab
                ? "bg-yellow-100 text-yellow-800"
                : "text-gray-500 hover:bg-gray-100"
            }`}
            onClick={() => setActiveTab(tab as "given" | "my")}
          >
            {tab === "given" ? "Given Reviews" : "Received Reviews"}
          </button>
        ))}
      </div>

      {/* Review List */}
      <div>
        {activeTab === "given" ? (
          givenReviews.length > 0 ? (
            <div className="">
              {givenReviews.map((review: any) => (
                <div
                  key={review.id}
                  className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden mt-5"
                >
                  <div className="flex flex-col sm:flex-row gap-4 sm:gap-6 p-6">
                    {/* Image */}
                    <div className="flex-shrink-0 relative w-full sm:w-32 h-32 rounded-lg overflow-hidden border border-gray-200">
                      <Image
                        unoptimized
                        src={review?.listing?.images?.[0]}
                        alt={review?.listing?.product_name || "Product"}
                        fill
                        className="object-cover"
                        sizes="(max-width: 640px) 100vw, 128px"
                      />
                    </div>

                    {/* Details */}
                    <div className="flex-1">
                      <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-2 sm:gap-3">
                        <div>
                          <h2 className="text-lg font-semibold text-gray-900 capitalize mb-1">
                            {review.listing.product_name}
                          </h2>
                          <StarRating rating={review.rating} />
                        </div>
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                          {review.rating}.0
                        </span>
                      </div>

                      <div className="bg-gray-50 p-3 sm:p-4 rounded-lg mb-3 sm:mb-4">
                        <p className="text-gray-700 italic text-sm sm:text-base">
                          “{truncateDescriptionListing(review.comment)}”
                        </p>
                      </div>

                      {/* Reviewer Info */}
                      <div className="flex items-center mt-3 sm:mt-4">
                        <div className="flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10 rounded-full overflow-hidden border-2 border-white shadow-sm">
                          <Image
                            unoptimized
                            src={review.listing.user.profile_url}
                            alt={`${review.listing.user.first_name} ${review.listing.user.last_name}`}
                            width={40}
                            height={40}
                            className="object-cover"
                          />
                        </div>
                        <div className="ml-3">
                          <p className="text-sm font-medium text-gray-900">
                            {review.listing.user.first_name}{" "}
                            {review.listing.user.last_name}
                          </p>
                          <p className="text-xs text-gray-500">
                            Purchased on{" "}
                            {new Date(review.created_at).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No reviews given yet"
              subtitle="Your feedback helps sellers improve their products and services."
              buttonText="Browse Purchases"
              icon={
                <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="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"
                  />
                </svg>
              }
            />
          )
        ) : receivedReviews.length > 0 ? (
          <div className="">
            {receivedReviews.map((review: any) => (
              <div
                key={review.id}
                className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden mt-5"
              >
                <div className="flex flex-col sm:flex-row gap-4 sm:gap-6 p-6">
                  {/* Image */}
                  <div className="flex-shrink-0 relative w-full sm:w-32 h-32 rounded-lg overflow-hidden border border-gray-200">
                    <Image
                      unoptimized
                      src={review?.listing?.images?.[0]}
                      alt={review?.listing?.product_name || "Product"}
                      fill
                      className="object-cover"
                      sizes="(max-width: 640px) 100vw, 128px"
                    />
                  </div>

                  {/* Details */}
                  <div className="flex-1">
                    <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-2 sm:gap-3">
                      <div>
                        <h2 className="text-lg font-semibold text-gray-900 capitalize mb-1">
                          {review.listing.product_name}
                        </h2>
                        <StarRating rating={review.rating} />
                      </div>
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                        {review.rating}.0
                      </span>
                    </div>

                    <div className="bg-gray-50 p-3 sm:p-4 rounded-lg mb-3 sm:mb-4">
                      <p className="text-gray-700 italic text-sm sm:text-base">
                        “{truncateDescriptionListing(review.comment)}”
                      </p>
                    </div>

                    {/* Reviewer Info */}
                    <div className="flex items-center mt-3 sm:mt-4">
                      <div className="flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10 rounded-full overflow-hidden border-2 border-white shadow-sm">
                        <Image
                          unoptimized
                          src={review.buyer?.profile_url}
                          alt={`${review.buyer?.first_name || ""} ${
                            review.buyer?.last_name || ""
                          }`}
                          width={40}
                          height={40}
                          className="object-cover"
                        />
                      </div>
                      <div className="ml-3">
                        <p className="text-sm font-medium text-gray-900">
                          {review.buyer?.first_name} {review.buyer?.last_name}
                        </p>
                        <p className="text-xs text-gray-500">
                          Purchased on{" "}
                          {new Date(review.created_at).toLocaleDateString()}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <EmptyState
            title="No reviews received yet"
            subtitle="Customer feedback will appear here after they review your products."
            buttonText="View Your Listings"
            icon={
              <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>
    </div>
  );
}

export default Page;
