import React, { useEffect, useState, useCallback } from "react";
import AdminHeader from "../../components/admin-header";
import Sidebar from "../../components/sidebar";
import { useLocation, useNavigate } 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";
import toast from "react-hot-toast";

const Vitrine = () => {
  const navigate = useNavigate();
  const location = useLocation(); // برای گرفتن URL
  const [loading, setLoading] = useState(false);
  const [vitrineList, setVitrineList] = useState([]);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  const [filters, setFilters] = useState({
    startDate: "",
    endDate: "",
    status: "",
  });

  // گرفتن لیست تبلیغات
  const getVitrineList = useCallback(
    (page = 1) => {
      setLoading(true);

      // چک کردن پارامتر URL
      const urlParams = new URLSearchParams(location.search);
      let statusParam = filters.status;

      if (urlParams.get("status") === "pending") {
        // اگر ?status=pending بود، فقط pre_payment نمایش بده
        statusParam = "pre_payment";
      }

      const { startDate, endDate } = filters;

      axios
        .get(
          `${BaseUrl}/advertising?limit=20&page=${page}${
            startDate ? "&startDate=" + startDate : ""
          }${endDate ? "&endDate=" + endDate : ""}${
            statusParam ? "&status=" + statusParam : ""
          }`
        )
        .then((res) => {
          setVitrineList(res?.data?.advertisings || []);
          setTotalPages(res?.data?.totalPages || 0);
        })
        .catch(() => {
          toast.error("خطا در دریافت اطلاعات");
        })
        .finally(() => setLoading(false));
    },
    [filters, location.search]
  );

  useEffect(() => {
    getVitrineList(currentPage);
  }, [currentPage, filters, getVitrineList]);

  // تغییر وضعیت تبلیغ
  const toggleVitrineStatus = (id, currentStatus) => {
    const newStatus = currentStatus === "accepted" ? "rejected" : "accepted";
    setLoading(true);

    axios
      .post(
        `${BaseUrl}/advertising/accept`,
        { advertisingId: id, status: newStatus },
        { headers: { "Content-Type": "application/json" } }
      )
      .then((res) => {
        toast.success(
          res?.data?.message ||
            `تبلیغ ${newStatus === "accepted" ? "تأیید" : "رد"} شد`
        );
        getVitrineList(currentPage); // ریفرش لیست
      })
      .catch((error) => {
        const errorMessage =
          error.response?.data?.message || "خطا در تغییر وضعیت تبلیغ";
        toast.error(errorMessage);
      })
      .finally(() => setLoading(false));
  };

  const rejectAdvertisingWithReason = async (id) => {
    const rejectReason = prompt("لطفاً دلیل رد را وارد کنید:");
    if (!rejectReason) return;
  
    setLoading(true);
    try {
     
      const response = await axios.post(
        `${BaseUrl}/advertising/reject`,
        { advertisingId: id, rejectReason },
        { headers: { "Content-Type": "application/json" } }
      );
  
      toast.success(response.data.message || "تبلیغ رد شد");
      getVitrineList(currentPage);
    } catch (error) {
      toast.error(error.response?.data?.message || "خطا در رد تبلیغ");
    } finally {
      setLoading(false);
    }
  };
  

  // console.log(vitrineList);

  return (
    <>
      <div className="min-h-screen mx-auto bg-gray-900">
        <div className="flex h-full w-full">
          <div className="w-64">
            <Sidebar />
          </div>
          <div className="w-full h-full p-14 mb-11 mx-auto  text-white">
            {/* فیلتر */}
            <Filters
              statusOptions={[
                { key: "", label: "همه" },
                { key: "pre_payment", label: "در انتظار پرداخت" },
                { key: "paid", label: "پرداخت شده" },
                { key: "accepted", label: "تأیید شده" },
                { key: "rejected", label: "رد شده" },
                { key: "expired", 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="w-[13%]">نام و نام خانوادگی</div>
                <div className="w-[13%]">دسته‌بندی</div>
                <div className="w-[13%]">عنوان تبلیغ</div>
                <div className="w-[13%]">استان</div>
                <div className="w-[13%]">شهر</div>
                <div className="w-[13%]">محله</div>
                <div className="w-[10%]">وضعیت</div>
                <div className="w-[12%] text-center">عملیات</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">
                {vitrineList?.map((vitrine, index) => (
                  <div
                    key={vitrine?._id}
                    className="w-full mt-2 flex items-center"
                  >
                    <div
                      className={`flex-1 w-full flex items-center h-[80px] px-5 rounded-lg ${
                        index % 2 === 0 ? "bg-[#c0e2f04b]" : "bg-[#678fa062]"
                      }`}
                    >
                      <div className="w-[13%]">
                        {vitrine?.creator_id?.first_name}{" "}
                        {vitrine?.creator_id?.last_name}
                      </div>
                      <div className="w-[13%]">{vitrine?.category}</div>
                      <div className="w-[13%]">{vitrine?.title}</div>
                      <div className="w-[13%]">{vitrine?.province?.name}</div>
                      <div className="w-[13%]">{vitrine?.city?.name}</div>
                      <div className="w-[13%]">{vitrine?.neighbourhood}</div>
                      <div className="w-[10%]">
                        <span
                          className={`${
                            vitrine?.status === "pre_payment"
                              ? "text-yellow-400"
                              : vitrine?.status === "paid"
                              ? "text-green-400"
                              : vitrine?.status === "accepted"
                              ? "text-green-300"
                              : vitrine?.status === "rejected"
                              ? "text-red-400"
                              : "text-gray-400"
                          }`}
                        >
                          {vitrine?.status === "pre_payment"
                            ? "در انتظار پرداخت"
                            : vitrine?.status === "paid"
                            ? "پرداخت شده"
                            : vitrine?.status === "accepted"
                            ? "تأیید شده"
                            : vitrine?.status === "rejected"
                            ? "رد شده"
                            : "منقضی شده"}
                        </span>
                      </div>

                      {/* دکمه عملیات */}
                      <div className="w-[12%] flex justify-center gap-2">
                        <button
                          onClick={() => navigate(`${vitrine?._id}`)}
                          className="bg-[#1f5f79] hover:bg-[#247392] px-4 h-[35px] rounded-md duration-300"
                        >
                          جزئیات
                        </button>
                        {vitrine?.status !== "expired" && (
                          <>
                          <button
                            onClick={() =>
                              toggleVitrineStatus(vitrine?._id, vitrine?.status)
                            }
                            className={`${
                              vitrine?.status === "accepted"
                                ? "bg-red-600 hover:bg-red-700 hidden"
                                : "bg-green-600 hover:bg-green-700"
                            } px-4 h-[35px] rounded-md duration-300`}
                          >
                            {vitrine?.status === "accepted" ? "رد" : "تأیید"}
                          </button>
                          <button
                          onClick={() => rejectAdvertisingWithReason(vitrine?._id)}
                          className={`${vitrine?.status === "accepted" ? "" : "hidden"} bg-red-600 hover:bg-red-700 px-4 h-[35px] rounded-md duration-300`}
                        >
                          رد با دلیل
                        </button>
                        </>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* صفحه‌بندی */}
            <Pagination
              totalItems={vitrineList.length}
              totalPages={totalPages}
              currentPage={currentPage}
              onPageChange={(page) => setCurrentPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default Vitrine;
