import React, { useEffect, useState } from "react";
import Cookies from "js-cookie";
import apiInterceptor from "@/interceptor/interceptor";
import toast, { Toaster } from "react-hot-toast";
import Swal from "sweetalert2";
const Index = () => {
  const [reviews, setReviews] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);

  const successNotify = () => toast.success("Review Deleted Successfully!");
  const errorNotify = () => toast.error("Something went wrong!");

  useEffect(() => {
    getReviews();
  }, [currentPage]);

  const getReviews = async () => {
    try {
      const accessToken = Cookies.get("jazz_token");

      const response = await apiInterceptor.get(
        `/api/review?page=${currentPage}`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );

      // API response ke according adjust kar lena
      setReviews(response.data.users?.data || response.data.data || []);

      setTotalPage(
        response.data.users?.pagination?.total_pages ||
          response.data.pagination?.total_pages ||
          1
      );
    } catch (error) {
      console.error(error);
      errorNotify();
    }
  };
const handleDelete = async (reviewId: string) => {
  const result = await Swal.fire({
    title: "Delete Review?",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#ef4444",
    cancelButtonColor: "#6b7280",
    confirmButtonText: "Yes, Delete",
    cancelButtonText: "Cancel",
  });

  if (!result.isConfirmed) return;

  try {
    const accessToken = Cookies.get("jazz_token");

    await apiInterceptor.delete(
      `/api/admin/deleteReview?reviewId=${reviewId}`,
      {
        headers: {
          authorization: `Bearer ${accessToken}`,
        },
      }
    );

    setReviews((prev) =>
      prev.filter((review) => review.id !== reviewId)
    );

    Swal.fire({
      title: "Deleted!",
      text: "Review deleted successfully.",
      icon: "success",
      timer: 1500,
      showConfirmButton: false,
    });
  } catch (error) {
    console.error(error);

    Swal.fire({
      title: "Error!",
      text: "Failed to delete review.",
      icon: "error",
    });
  }
};

  return (
    <>
      <Toaster />

      <div className="p-6">
        <h1 className="text-2xl font-semibold mb-6">
          Reviews Management
        </h1>

        <div className="overflow-x-auto rounded-lg shadow">
          <table className="min-w-full bg-white">
            <thead className="bg-gray-800 text-white">
              <tr>
                <th className="px-4 py-3 text-left">#</th>
                <th className="px-4 py-3 text-left">User Name</th>
                <th className="px-4 py-3 text-left">Review</th>
                <th className="px-4 py-3 text-center">Action</th>
              </tr>
            </thead>

            <tbody>
              {reviews.length > 0 ? (
                reviews.map((item, index) => (
                  <tr
                    key={item.id}
                    className="border-b hover:bg-gray-100"
                  >
                    <td className="px-4 py-3">
                      {(currentPage - 1) * 10 + index + 1}
                    </td>

                    <td className="px-4 py-3">
                      {item.userName || "-"}
                    </td>

           

                    <td className="px-4 py-3 max-w-md">
                      {item.description}
                    </td>

             

                    <td className="px-4 py-3 text-center">
                      <button
                        onClick={() => handleDelete(item.id)}
                        className="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded"
                      >
                        Delete
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td
                    colSpan={6}
                    className="text-center py-6 text-gray-500"
                  >
                    No Reviews Found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex justify-between mt-6">
          <button
            disabled={currentPage === 1}
            onClick={() => setCurrentPage((prev) => prev - 1)}
            className="bg-gray-700 text-white px-4 py-2 rounded disabled:opacity-50"
          >
            Previous
          </button>

          <span className="font-medium">
            Page {currentPage} of {totalPage}
          </span>

          <button
            disabled={currentPage === totalPage}
            onClick={() => setCurrentPage((prev) => prev + 1)}
            className="bg-gray-700 text-white px-4 py-2 rounded disabled:opacity-50"
          >
            Next
          </button>
        </div>
      </div>
    </>
  );
};

export default Index;