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, ImageBaseUrl } from "../../components/BaseUrl";
import axios from "axios";
import Loading from "../../components/elements/loading";
import toast from "react-hot-toast";
import Pagination from "../../components/Pagination";
import Filters from "../../components/Filters";

const Posts = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const statusParam = searchParams.get("status"); // مقدار پارامتر status
  const [loading, setLoading] = useState(false);
  const [postsList, setPostsList] = useState([]); // آرایه خالی به عنوان مقدار اولیه
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [filters, setFilters] = useState({
    startDate: "",
    endDate: "",
    status: "",
  });

  const getPostList = (page = 1) => {
    setLoading(true);

    const { startDate, endDate, status } = filters;
    const finalStatus = statusParam || status;

    const config = {
      url: `${BaseUrl}/posts?limit=10&page=${page}${
        startDate ? "&startDate=" + startDate : ""
      }${endDate ? "&endDate=" + endDate : ""}&status=${finalStatus}`,
      method: "GET",
    };
    axios(config)
      .then((res) => {
        setPostsList(res?.data?.posts || []);
        setTotalPages(res?.data?.totalPages || 0);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Error fetching posts:", err);
        toast.error(
          "خطا در دریافت پست‌ها: " +
            (err.response?.data?.message || err.message)
        );
        setPostsList([]);
        setTotalPages(0);
        setLoading(false);
      });
  };

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

  const togglePostAccept = (_id, user_id, status) => {
    const data = {
      id: _id,
      user_id,
      status: status === "accept" ? "reject" : "accept",
    };
    axios
      .post(`${BaseUrl}/posts/accept`, data, {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      })
      .then((response) => {
        toast.success(response?.data?.message);
        getPostList(currentPage); // بارگذاری مجدد لیست پست‌ها
      })
      .catch((error) => {
        console.error("Error toggling post status:", error);
        toast.error(error?.response?.data?.message || "خطای ناشناخته");
      });
  };

  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: "pending", label: "درانتظار تایید" },
                { key: "accept", label: "منتشر شده" },
                { key: "reject", 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-[10%]">
                  <p className="font-KalamehMed text-sm font-medium">تصویر</p>
                </div>
                <div className="col-span-1 w-[10%]">
                  <p className="font-KalamehMed text-sm font-medium">
                    نام کاربری
                  </p>
                </div>
                <div className="col-span-1 w-[10%]">
                  <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-[10%]">
                  <p className="font-KalamehMed text-sm font-medium">موبایل</p>
                </div>
                <div className="col-span-1 w-[10%]">
                  <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-[16%]">
                  <p className="font-KalamehMed text-sm font-medium">وضعیت</p>
                </div>
                <div className="col-span-1 w-[10%]">
                  <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>
            ) : postsList.length === 0 ? (
              <div className="w-full flex items-center justify-center mt-5">
                <p className="font-KalamehMed text-sm font-medium text-gray-400">
                  هیچ پستی یافت نشد
                </p>
              </div>
            ) : (
              <div className="w-full">
                {postsList.map((post, index) => (
                  <div
                    key={post._id}
                    className="w-full mt-4 flex items-center bg-[#252525]"
                  >
                    <div
                      className={`flex-1 w-full flex items-center h-[90px] px-5 rounded-lg py-8 ${
                        index % 2 === 0 ? "bg-[#c0e2f04b]" : "bg-[#678fa062]"
                      }`}
                    >
                      {/* تصویر / ویدیو */}
                      <div className="col-span-1 w-[10%]">
                        <div className="flex items-center">
                          {post?.files?.length > 0 ? (
                            post.files[0].type === "image" ? (
                              <img
                                className="w-[80px] h-[80px] rounded-md ml-2 object-cover"
                                src={`${ImageBaseUrl}${post.files[0].path.replace(
                                  "/root/modstagram-back/storage",
                                  ""
                                )}`}
                                alt="Post"
                              />
                            ) : (
                              <video
                                className="w-[80px] h-[80px] rounded-md ml-2 object-cover"
                                src={`${ImageBaseUrl}${post.files[0].path.replace(
                                  "/root/modstagram-back/storage",
                                  ""
                                )}`}
                                controls
                              />
                            )
                          ) : (
                            <img
                              className="w-[80px] h-[80px] rounded-md ml-2 object-cover"
                              src="/images/placeholder.jpg"
                              alt="No file"
                            />
                          )}
                        </div>
                      </div>

                      {/* نام کاربری */}
                      <div className="col-span-1 w-[10%]">
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.user_name || "-"}
                        </p>
                      </div>

                      {/* نوع کاربری */}
                      <div className="col-span-1 w-[10%]">
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.user_type === "employer"
                            ? "کارفرما"
                            : post?.user_type === "user"
                            ? post?.expertise || "-"
                            : "-"}
                        </p>
                      </div>

                      {/* نام و نام خانوادگی */}
                      <div className="col-span-1 w-[12%]">
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.first_name && post?.last_name
                            ? `${post.first_name} ${post.last_name}`
                            : "-"}
                        </p>
                      </div>

                      {/* موبایل */}
                      <div className="col-span-1 w-[10%]">
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.mobile || "-"}
                        </p>
                      </div>

                      {/* کد ملی */}
                      <div className="col-span-1 w-[10%]">
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.national_code || "-"}
                        </p>
                      </div>

                      {/* تاریخ */}
                      <div className="col-span-1 w-[12%]">
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.createdAt || "-"}
                        </p>
                      </div>

                      {/* وضعیت */}
                      <div className="col-span-1 w-[16%]">
                        <div className="flex items-center">
                          <p
                            className={`font-KalamehMed text-sm font-medium ${
                              post?.status === "accept"
                                ? "text-green-300"
                                : post?.status === "pending"
                                ? "text-yellow-300"
                                : "text-red-300"
                            }`}
                          >
                            {post?.status === "accept"
                              ? "منتشر شده"
                              : post?.status === "pending"
                              ? "در انتظار تایید"
                              : "رد شده"}
                          </p>
                        </div>
                      </div>

                      {/* دکمه‌ها */}
                      <div className="col-span-1 w-[10%]">
                        <button
                          onClick={() => navigate(`${post?._id}`)}
                          className="bg-[#1f5f79] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300 mr-5"
                        >
                          جزئیات
                        </button>
                        <button
                          onClick={() =>
                            togglePostAccept(
                              post._id,
                              post.user_id,
                              post.status
                            )
                          }
                          className={`ml-2 px-4 h-[35px] rounded-md duration-300 ${
                            post.status === "accept"
                              ? "bg-red-500 hover:bg-red-600"
                              : "bg-green-500 hover:bg-green-600"
                          }`}
                        >
                          {post.status === "accept" ? "رد" : "تایید"}
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <Pagination
              totalItems={postsList.length}
              totalPages={totalPages}
              currentPage={currentPage}
              onPageChange={(page) => setCurrentPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default Posts;
