import React, { useEffect, useState } from "react";
import AdminHeader from "../../components/admin-header";
import Sidebar from "../../components/sidebar";
import { useNavigate, useSearchParams } from "react-router-dom";
import { BaseUrl } from "../../components/BaseUrl";
import axios from "axios";
import Loading from "../../components/elements/loading";
import Pagination from "../../components/Pagination";
import Filters from "../../components/Filters";

const Comments = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [commentList, setCommentList] = useState([]);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  // 
  const [filters, setFilters] = useState({ startDate: "", endDate: "", status: "" });


  const [searchParams] = useSearchParams();
  const statusParam = searchParams.get("status"); // مثلا "pending"
  const token = document.cookie
  .split('; ')
  .find(row => row.startsWith('token='))
  ?.split('=')[1];
 

  const getCommentList = (page = 1) => {
    setLoading(true);
    // 
    
    const { startDate, endDate , status} = filters;
    const config = {
      url: `${BaseUrl}/comments?limit=20&page=${page}${startDate ? "&startDate=" + startDate : ""}${endDate ? "&endDate=" + endDate : ""}&status=${statusParam? "pending" : status}`,
    
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}` // اضافه کردن توکن به هدر
      }
    };
    axios(config)
      .then((res) => {
        setCommentList(res?.data?.comments);
        setTotalPages(res?.data?.totalPages);  // دریافت تعداد صفحات از API
        setLoading(false);
      })
      .catch((err) => {
        // console.log("Error in getCommentList:", err.response?.status, err.response?.data || err.message);
        console.log("Full error object:", JSON.stringify(err, null, 2));
        console.log("Message:", err.message);
        console.log("Response:", err.response);
        setLoading(false);
      });
      
  };
  useEffect(() => {
    getCommentList(currentPage);
  }, [currentPage, filters]);

  return (
    <>
      <div className="min-h-screen mx-auto bg-gray-900">
        <div className="flex h-full w-full">
          <div className="bg-[#1f5f79] w-64">
            <Sidebar />
          </div>
          <div className="w-full h-full p-14 mb-11 mx-auto  text-white">
            {/* Filters */}
            <Filters
              statusOptions={[
                { key: "", label: "همه" },
                { key: "pending", label: "در انتظار تایید" },
                { key: "accepted", label: "تایید شده" },
                { key: "rejected", label: "رد شده" },
              ]}
              provinceOptions={[{ value: "", label: "همه استان‌ها" }]}
              cityOptions={[{ value: "", label: "همه شهرها" }]}
              photographyModelOptions={[{ value: "", label: "همه مدل‌ها" }]}
              blockStatusOptions={[{ value: "", label: "همه کاربران" }]}
              onFilterChange={setFilters}
            />

            <div className="w-full mt-4 flex items-center  border-b ">
              <div className="flex-1 w-full flex items-center h-11 px-5">
                <div className="col-span-1 w-[13%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    عنوان پروژه
                  </p>
                </div>
                <div className="col-span-1  w-[13%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    نام کاربری سازنده
                  </p>
                </div>
                <div className="col-span-1  w-[13%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    نام و نام خانوادگی سازنده
                  </p>
                </div>
                <div className="col-span-1  w-[13%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    نام کاربری یوزر
                  </p>
                </div>
                <div className="col-span-1  w-[13%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    نام و نام خانوادگی یوزر
                  </p>
                </div>
                <div className="col-span-1  w-[13%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    تاریخ ثبت کامنت
                  </p>
                </div>
                <div className="col-span-1  w-[12%]">
                  <p className="font-KalamehMed text-sm font-medium">وضعیت</p>
                </div>
                <div className="col-span-1 w-[11%]">
                  <p className="font-KalamehMed text-sm font-medium"></p>
                </div>
              </div>
            </div>
            {loading ? (
              <div className="w-full flex items-center justify-center mt-5">
                <Loading className="w-14 h-14 text-blacklead animate-pulse" />
              </div>
            ) : (
              <div className="overflow-y-scroll hide-scrollbar w-full">
                {Array.isArray(commentList) && commentList.length > 0 ? (
                  commentList.map((comment, index) => {
                    

                    return (
                      <div
                        key={comment?._id || index}
                        className={`flex-1 w-full flex items-center h-[90px] px-5 py-8 rounded-lg ${
                          index % 2 === 0 ? "bg-[#c0e2f04b]" : "bg-[#678fa062]"
                        }`}
                      >
                        <div className="col-span-1 w-[13%]">
                          <p className="font-KalamehMed text-sm font-medium mr-2">
                            {comment?.project || "-"}
                          </p>
                        </div>
                        <div className="col-span-1 w-[13%]">
                          <p className="font-KalamehMed text-sm font-medium mr-2">
                            {comment?.creator?.user_name || "-"}
                          </p>
                        </div>
                        <div className="col-span-1 w-[13%]">
                          <p className="font-KalamehMed text-sm font-medium mr-2">
                            {comment?.creator?.first_name || ""}{" "}
                            {comment?.creator?.last_name || ""}
                          </p>
                        </div>
                        <div className="col-span-1 w-[13%]">
                          <p className="font-KalamehMed text-sm font-medium mr-2">
                            {comment?.user?.user_name || "-"}
                          </p>
                        </div>
                        <div className="col-span-1 w-[13%]">
                          <p className="font-KalamehMed text-sm font-medium mr-2">
                            {comment?.user?.first_name || ""}{" "}
                            {comment?.user?.last_name || ""}
                          </p>
                        </div>
                        <div className="col-span-1 w-[13%]">
                          <p className="font-KalamehMed text-sm font-medium mr-2">
                            {comment?.createdAt || "-"}
                          </p>
                        </div>
                        <div className="col-span-1 w-[12%]">
                          <div className="flex items-center">
                            <p
                              className={`font-KalamehMed text-sm font-medium ${
                                comment?.status === "pending"
                                  ? "text-yellow-400"
                                  : comment?.status === "accepted"
                                  ? "text-green-400"
                                  : "text-red-400"
                              }`}
                            >
                              {comment?.status === "pending"
                                ? "در انتظار تایید"
                                : comment?.status === "accepted"
                                ? "تایید شده"
                                : comment?.status === "rejected"
                                ? "رد شده"
                                : "-"}
                            </p>
                          </div>
                        </div>
                        <div className="col-span-1 w-[11%]">
                          <button
                            onClick={() => navigate(`${comment?._id}`)}
                            className="bg-[#1f5f79] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300 mr-5"
                          >
                            جزئیات
                          </button>
                        </div>
                      </div>
                    );
                  })
                ) : (
                  <p className="text-center text-gray-400 mt-6">
                    هیچ کامنتی یافت نشد.
                  </p>
                )}
              </div>
            )}
            <Pagination
              totalItems={commentList.length}
              totalPages={totalPages}
              currentPage={currentPage}
              onPageChange={(page) => setCurrentPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default Comments;
