import React, { useState } from "react";
import { BaseUrl, ImageBaseUrl } from "../BaseUrl";
import axios from "axios";
import Modal from "react-modal";
import toast from "react-hot-toast";
import Sidebar from "../sidebar";

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

const UserDet = ({ userData, id, getUserDet }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editedData, setEditedData] = useState({});
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [modalImage, setModalImage] = useState("");

  const openModal = (image) => {
    setModalImage(image);
    setModalIsOpen(true);
  };

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

  const handleChange = (e) => {
    const { name, value } = e.target;
    setEditedData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSave = async () => {
    try {
      const response = await axios.put(
        `${BaseUrl}/users/update?userId=${userData._id}`,
        editedData,
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );
      setIsEditing(false);
      toast.success("اطلاعات با موفقیت ذخیره شد");
      getUserDet();
    } catch (error) {
      if (error.response && error.response.data && error.response.data.errors) {
        error.response.data.errors.forEach((err) => {
          toast.error(
            typeof err.message === "string" ? err.message : "خطای ناشناخته"
          );
        });
      } else {
        toast.error("خطای ناشناخته");
      }
    }
  };

  const acceptVerify = () => {
    axios
      .post(`${BaseUrl}/users/verify?userId=${id}`, {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      })
      .then(async (response) => {
        toast.success(response?.data?.message);
        getUserDet();
      })
      .catch((error) => {
        toast.error(error?.response?.data?.message || "خطای ناشناخته");
      });
  };

  const rejectVerify = () => {
    axios
      .post(`${BaseUrl}/users/reject?userId=${id}`, {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      })
      .then(async (response) => {
        toast.success(response?.data?.message);
        getUserDet();
      })
      .catch((error) => {
        toast.error(error?.response?.data?.message || "خطای ناشناخته");
      });
  };

  const acceptService = async (serviceId) => {
    try {
      // به‌روزرسانی آرایه services با تغییر status سرویس موردنظر به "true"
      const updatedServices = userData.services.map((service) =>
        service._id === serviceId ? { ...service, status: "true" } : service
      );

      const response = await axios.put(
        `${BaseUrl}/users/update?userId=${userData._id}`,
        { services: updatedServices },
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
        }
      );
      toast.success(response?.data?.message || "سرویس با موفقیت تأیید شد");
      getUserDet();
    } catch (error) {
      toast.error(error?.response?.data?.message || "خطای ناشناخته");
    }
  };

  const rejectService = async (serviceId) => {
    // فقط پیام رد نمایش داده می‌شود و status تغییر نمی‌کند
    toast.success("سرویس رد شد");
  };

  return (
    <div className=" gap-3 ">
      <div className="flex flex-col  justify-center items-center gap-5 mt-5">
        <Modal
          isOpen={modalIsOpen}
          onRequestClose={closeModal}
          className="post-image-modal "
          style={customStyles}
        >
          <img src={modalImage} alt="Post" className="post-modal-image" />
        </Modal>

        {/* Profile Image */}
        <div className="flex items-center w-full ">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            تصویر پروفایل:
          </div>
          <div className="flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 p-4">
            <img
              onClick={() => openModal(ImageBaseUrl + userData?.profile_image)}
              src={ImageBaseUrl + userData?.profile_image}
              className="w-[200px] h-[200px] rounded-md"
              alt=""
            />
          </div>
        </div>

        {/* User Name */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            نام کاربری:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="user_name"
                defaultValue={userData.user_name}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.user_name
            )}
          </div>
        </div>

        {/* First Name */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            نام:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="first_name"
                defaultValue={userData.first_name}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.first_name
            )}
          </div>
        </div>

        {/* Last Name */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            نام خانوادگی:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="last_name"
                defaultValue={userData.last_name}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.last_name
            )}
          </div>
        </div>

        {/* Mobile */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            موبایل:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="mobile"
                defaultValue={userData.mobile}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.mobile
            )}
          </div>
        </div>

        {/* National Code */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            کد ملی:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="national_code"
                defaultValue={userData.national_code}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.national_code
            )}
          </div>
        </div>

        {/* Province */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            استان:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.province?.name}
          </div>
        </div>

        {/* City */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            شهر:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.city?.name}
          </div>
        </div>

        {/* Address */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            آدرس:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="address"
                defaultValue={userData.address}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.address
            )}
          </div>
        </div>

        {/* Height */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            قد:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="height"
                defaultValue={userData.height}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.height
            )}
          </div>
        </div>

        {/* Weight */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            وزن:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="weight"
                defaultValue={userData.weight}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.weight
            )}
          </div>
        </div>

        {/* Size */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            سایز:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="size"
                defaultValue={userData.size}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.size
            )}
          </div>
        </div>

        {/* Bio */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            بیو:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="bio"
                defaultValue={userData.bio}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.bio
            )}
          </div>
        </div>

        {/* Birthday */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            تاریخ تولد:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.birthday}
          </div>
        </div>

        {/* Cooperation Abroad */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            خارج از محدوده سکونت به من پیشنهاد بده:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.cooperation_abroad == true ? "بله" : "خیر"}
          </div>
        </div>

        {/* Conversation Projects */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            پروژه با روابط عمومی بالا:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.conversation_projects == true ? "بله" : "خیر"}
          </div>
        </div>

        {/* Expertise */}
        <div className="flex items-start w-full gap-3">
          {/* عنوان */}
          <div className="w-[180px] flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            تخصص:
          </div>

          {/* تخصص + زیرتخصص‌ها */}
          <div className="flex flex-wrap gap-1 font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4 py-2 flex-1">
            <span>{userData?.expertise} :</span>

            {userData?.sub_expertise?.map((item, index) => (
              <span key={index}>
                {item}
                {index !== userData?.sub_expertise?.length - 1 ? " _ " : ""}
              </span>
            ))}
          </div>
        </div>

        {/* Shaba */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            شماره شبا:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {isEditing ? (
              <input
                type="text"
                name="shaba"
                defaultValue={userData.shaba}
                onChange={handleChange}
                className="bg-[#222] text-primary px-2 py-1 rounded-md w-full min-h-9"
              />
            ) : (
              userData?.shaba
            )}
          </div>
        </div>

        {/* National Card Image */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            تصویر کارت ملی:
          </div>
          <div className="flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 p-4">
            <img
              onClick={() =>
                openModal(ImageBaseUrl + userData?.national_card_image)
              }
              src={ImageBaseUrl + userData?.national_card_image}
              className="w-[200px] h-[200px] rounded-md"
              alt=""
            />
          </div>
        </div>

        {/* Last Online */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            آخرین زمان ورود:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.last_online}
          </div>
        </div>

        {/* Created At */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            تاریخ ثبت نام:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.createdAt}
          </div>
        </div>

        {/* Verification Status */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            وضعیت مدارک:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            <p className="font-KalamehMed text-sm font-medium">
              {userData?.is_verified === "verified"
                ? "تایید شده"
                : userData?.is_verified === "pending"
                ? "در انتظار تایید"
                : ""}
            </p>
            <button
              onClick={() => acceptVerify()}
              className="bg-[#146820] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300 mr-3"
            >
              تایید مدارک
            </button>
            <button
              onClick={() => rejectVerify()}
              className="bg-[#a02121d3] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300 mr-3"
            >
              رد مدارک
            </button>
          </div>
        </div>

        {/* Services Section */}
        <div className="flex items-start w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            خدمات:
          </div>
          <div className="flex flex-col gap-4 font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4 py-4">
            {userData?.services?.length > 0 ? (
              userData.services.map((service) => (
                <div
                  key={service._id}
                  className="flex items-center gap-4 p-4 bg-[#222] rounded-lg"
                >
                  <img
                    src={ImageBaseUrl + service.image}
                    alt={service.title}
                    className="w-[100px] h-[100px] rounded-md cursor-pointer"
                    onClick={() => openModal(ImageBaseUrl + service.image)}
                  />
                  <div className="flex flex-col gap-2">
                    <p>عنوان: {service.title}</p>
                    <p>قیمت اصلی: {service.originalPrice} تومان</p>
                    <p>قیمت با تخفیف: {service.discountPrice} تومان</p>
                    <p>درصد تخفیف: {service.discountPercentage}%</p>
                    <p>
                      وضعیت:{" "}
                      {service.status === "true"
                        ? "تأیید شده"
                        : service.status === "UnderReview"
                        ? "در انتظار بررسی"
                        : "رد شده"}
                    </p>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => acceptService(service._id)}
                      className={`bg-[#146820] hover:bg-[#247392] px-4 h-[35px] rounded-md duration-300 ${
                        service.status === "true" ? "hidden" : ""
                      }`}
                      disabled={service.status === "true"}
                    >
                      تأیید
                    </button>
                  </div>
                </div>
              ))
            ) : (
              <p>هیچ سرویسی یافت نشد</p>
            )}
          </div>
        </div>

        {/* User Rate */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            امتیاز کاربر:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.rate}
          </div>
        </div>

        {/* User Level */}
        <div className="flex items-center w-full">
          <div className="w-[180px] ml-3 flex items-center font-medium font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            سطح کاربر:
          </div>
          <div className="flex items-center font-medium min-w-[500px] font-KalamehMed text-sm text-primary rounded-lg bg-[#111] min-h-14 px-4">
            {userData?.user_level}
          </div>
        </div>

        {/* Save Button */}
        <div className="flex items-center w-full">
          {isEditing ? (
            <button
              onClick={handleSave}
              className="bg-[#146820] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300"
            >
              ذخیره
            </button>
          ) : (
            <button
              onClick={() => setIsEditing(!isEditing)}
              className="bg-[#146820] hover:bg-[#247392] px-8 h-[35px] rounded-md duration-300 mr-3"
            >
              ویرایش
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default UserDet;
