import React, { useEffect, useState } from "react";
import Sidebar from "../../components/sidebar";
import { useNavigate, useParams } 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 Modal from "react-modal";

const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    position: "fixed",
    background: "transparent",
    border: "none",
  },
};

const PostDetail = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [loading, setLoading] = useState(false);
  const [postDetails, setPostDetails] = useState({});
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [modalMedia, setModalMedia] = useState(null);

  const openModal = (media) => {
    setModalMedia(media);
    setModalIsOpen(true);
  };

  const closeModal = () => {
    setModalIsOpen(false);
    setModalMedia(null);
  };

  const getPostDetails = () => {
    setLoading(true);
    axios
      .get(`${BaseUrl}/posts/detail?post_id=${id}`)
      .then((res) => {
        setPostDetails(res?.data?.post || {});
        setLoading(false);
      })
      .catch((err) => {
        console.error("Error fetching post details:", err);
        toast.error(
          "خطا در دریافت جزئیات پست: " +
            (err.response?.data?.message || err.message)
        );
        setPostDetails({});
        setLoading(false);
      });
  };

  useEffect(() => {
    if (id) getPostDetails();
  }, [id]);

  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);
        getPostDetails();
      })
      .catch((error) => {
        console.error("Error toggling post status:", error);
        toast.error(error?.response?.data?.message || "خطای ناشناخته");
      });
  };

  return (
    <div className="min-h-screen mx-auto">
      <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 bg-[#252525] text-white">
          <div className="w-full flex items-center justify-between">
            <h4 className="font-medium font-KalamehMed text-lg">
              اطلاعات پست:
            </h4>
            <button
              onClick={() => navigate(-1)}
              className="flex gap-1 bg-[#1f5f79] font-semibold font-KalamehMed rounded-lg hover:bg-[#E0E3E3] transition-colors duration-500 p-[10px]"
            >
              بازگشت
            </button>
          </div>

          {loading ? (
            <div className="w-full flex items-center justify-center mt-5">
              <Loading className="w-14 h-14 text-blacklead animate-pulse" />
            </div>
          ) : !postDetails || Object.keys(postDetails).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="flex flex-col gap-5 pr-5 mt-5">
              {/* نمایش فایل‌های پست */}
              <div className="flex items-start w-full">
                <div className="w-[180px] ml-3 flex items-center font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
                  فایل‌های پست:
                </div>
                <div className="grid grid-cols-3 gap-3 bg-[#111] p-4 rounded-lg">
                  {postDetails?.files?.length > 0 ? (
                    postDetails.files.map((file, i) =>
                      file.type === "image" ? (
                        <img
                          key={i}
                          src={`${ImageBaseUrl}${file.path.replace(
                            "/root/modstagram-back/storage",
                            ""
                          )}`}
                          alt={`Post file ${i}`}
                          className="w-[200px] h-[200px] object-cover rounded-md cursor-pointer"
                          onClick={() =>
                            openModal({
                              type: "image",
                              src: `${ImageBaseUrl}${file.path.replace(
                                "/root/modstagram-back/storage",
                                ""
                              )}`,
                            })
                          }
                        />
                      ) : (
                        <video
                          key={i}
                          src={`${ImageBaseUrl}${file.path.replace(
                            "/root/modstagram-back/storage",
                            ""
                          )}`}
                          className="w-[200px] h-[200px] rounded-md cursor-pointer"
                          controls
                          onClick={() =>
                            openModal({
                              type: "video",
                              src: `${ImageBaseUrl}${file.path.replace(
                                "/root/modstagram-back/storage",
                                ""
                              )}`,
                            })
                          }
                        />
                      )
                    )
                  ) : (
                    <p className="text-gray-400">هیچ فایلی موجود نیست</p>
                  )}
                </div>
              </div>

              {/* کپشن */}
              <div className="flex items-center w-full">
                <div className="w-[180px] ml-3 flex items-center font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
                  کپشن:
                </div>
                <div className="flex items-center font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4 py-4">
                  {postDetails?.caption || "-"}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Modal برای نمایش بزرگ‌تر عکس/ویدیو */}
      <Modal
        isOpen={modalIsOpen}
        onRequestClose={closeModal}
        style={customStyles}
      >
        {modalMedia ? (
          modalMedia.type === "image" ? (
            <img
              src={modalMedia.src}
              alt="Post"
              className="max-w-[90vw] max-h-[90vh] rounded-lg"
            />
          ) : (
            <video
              src={modalMedia.src}
              controls
              className="max-w-[90vw] max-h-[90vh] rounded-lg"
            />
          )
        ) : null}
      </Modal>
    </div>
  );
};

export default PostDetail;
