import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { BaseUrl, ImageBaseUrl } from "../../components/BaseUrl";
import axios from "axios";
import Loading from "../../components/elements/loading";
import Pagination from "../../components/Pagination";

const UserPosts = ({ id }) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [allPosts, setAllPosts] = useState([]); // تمام پست‌ها
  const [postsList, setPostsList] = useState([]); // پست‌های صفحه جاری
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [filters, setFilters] = useState({
    startDate: "",
    endDate: "",
    status: "",
  });

  const itemsPerPage = 10; // تعداد آیتم در هر صفحه

  // دریافت همه پست‌ها از API (بدون user_id)
  const fetchAllPosts = () => {
    setLoading(true);
    const { startDate, endDate, status } = filters;

    let url = `${BaseUrl}/posts?limit=1000`; // گرفتن تعداد زیاد برای فیلتر فرانت
    if (startDate) url += `&startDate=${startDate}`;
    if (endDate) url += `&endDate=${endDate}`;
    if (status) url += `&status=${status}`;

    axios
      .get(url)
      .then((res) => {
        const posts = res?.data?.posts || [];
        setAllPosts(posts);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  };

  // فیلتر و صفحه‌بندی روی فرانت
  const paginatePosts = () => {
    const filteredPosts = allPosts.filter((post) => post.user_id === id);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const paginatedPosts = filteredPosts.slice(
      startIndex,
      startIndex + itemsPerPage
    );
    setPostsList(paginatedPosts);
    setTotalPages(Math.ceil(filteredPosts.length / itemsPerPage));
  };

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

  useEffect(() => {
    paginatePosts();
  }, [allPosts, currentPage, id]);

  return (
    <>
      <div className="min-h-screen mx-auto">
        <div className="flex h-full w-full">
          <div className="w-full h-full p-4 mb-11 mx-auto bg-[#252525] text-white">
            {/* Table Header */}
            <div className="w-full mt-4 flex items-center bg-[#252525] border-b">
              <div className="flex-1 w-full flex items-center h-11 px-5">
                <div className="w-[10%]">
                  <p>تصویر</p>
                </div>
                <div className="w-[10%]">
                  <p>نام کاربری</p>
                </div>
                <div className="w-[10%]">
                  <p>نوع کاربری</p>
                </div>
                <div className="w-[12%]">
                  <p>نام و نام خانوادگی</p>
                </div>
                <div className="w-[10%]">
                  <p>موبایل</p>
                </div>
                <div className="w-[10%]">
                  <p>کد ملی</p>
                </div>
                <div className="w-[12%]">
                  <p>تاریخ ثبت پست</p>
                </div>
                <div className="w-[16%]">
                  <p>وضعیت</p>
                </div>
                <div className="w-[10%]">
                  <p>جزئیات</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">
                {postsList?.map((post, index) => (
                  <div
                    key={post._id}
                    className={`w-full mt-4 flex items-center`}
                  >
                    <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="w-[10%]">
                        {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 className="w-[10%]">
                        <p>{post?.user_name}</p>
                      </div>
                      <div className="w-[10%]">
                        {" "}
                        <p className="font-KalamehMed text-sm font-medium">
                          {post?.user_type === "employer"
                            ? "کارفرما"
                            : post?.user_type === "user"
                            ? post?.expertise || "-"
                            : "-"}
                        </p>
                      </div>
                      <div className="w-[12%]">
                        <p>
                          {post?.first_name} {post?.last_name}
                        </p>
                      </div>
                      <div className="w-[10%]">
                        <p>{post?.mobile}</p>
                      </div>
                      <div className="w-[10%]">
                        <p>{post?.national_code}</p>
                      </div>
                      <div className="w-[12%]">
                        <p>{post?.createdAt}</p>
                      </div>
                      <div className="w-[16%]">
                        <p
                          className={
                            post?.status === "accept"
                              ? "text-green-300"
                              : post?.status === "pending"
                              ? "text-yellow-300"
                              : "text-red-300"
                          }
                        >
                          {post?.status === "accept"
                            ? "منتشر شده"
                            : post?.status === "pending"
                            ? "در انتظار تایید"
                            : "رد شده"}
                        </p>
                      </div>
                      <div className="w-[10%]">
                        <button
                          onClick={() => navigate(`/posts/${post?._id}`)}
                          className="bg-[#1f5f79] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300 mr-5"
                        >
                          جزئیات
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <Pagination
              totalItems={allPosts.filter((post) => post.user_id === id).length}
              totalPages={totalPages}
              currentPage={currentPage}
              onPageChange={(page) => setCurrentPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default UserPosts;
