import React, { useEffect, useState } from "react";
import { GoDotFill } from "react-icons/go";
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import { RxCross2 } from "react-icons/rx";
import {
  setViewImage,
  toggleProfileView,
} from "../../../store/Slices/ViewManagerSlice";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { useFile } from "../../../context/FileProvider";
import { useConversationInfo } from "../../../store/api/useConversationInfo";
import { ContactType, UpdateGroupRes } from "../../../types/ResType";
import { updateCurrentConversation } from "../../../store/Slices/CurrentConversationSlice";
import toast from "react-hot-toast";
import { socketInstance } from "../../../socket/socket";
import useApiPost from "../../../hooks/PostData";
import { BiEditAlt } from "react-icons/bi";
import { MdCheck } from "react-icons/md";
import TextTranslate from "../../../utils/TextTranslate";
import { useConversationMembers } from "../../../store/api/useConversationMembers";
import { updateByChatId } from "../../../store/Slices/ChatListSlice";

export default function GroupHeader() {
  // let { data } = useConversationInfo();
  const { setSelectedFile } = useFile();
  const { data: GroupMemberData } = useConversationMembers();
  const OnlineUserList = useAppSelector((state) => state.OnlineUserList);
  const [selectedFileUrl, setSelectedFileUrl] = useState("");
  const { postData } = useApiPost();
  const dispatch = useAppDispatch();
  const [editGroup, setEditGroup] = useState(false);
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const ContactList = useAppSelector((state) => state.ContactList);
  const [group_name, setGroup_name] = useState("");

  useEffect(() => {
    setGroup_name(currentConversationData.group_name!);
  }, [currentConversationData.group_name]);

  function closeSideBar() {
    dispatch(toggleProfileView(false));
  }

  const onFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedFile(null);
    const files = event.target.files![0];
    if (!files) return;
    setSelectedFile(files);
    setSelectedFileUrl(URL.createObjectURL(files));

    const editGroupFormData = new FormData();

    editGroupFormData.append(
      "chat_id",
      currentConversationData.chat_id.toString(),
    );
    editGroupFormData.append("group_icon", files!);
    editGroupFormData.append("pictureType", "group_icon");
    // Make the API call with the constructed FormData
    const updateGroupProfile: UpdateGroupRes = await postData(
      "chat/update-group",
      editGroupFormData,
      "multipart/form-data",
    );

    if (updateGroupProfile.status == true) {
      toast.success("Group Profile Updated", { position: "top-right" });
      dispatch(
        updateCurrentConversation({
          group_icon: updateGroupProfile.data.group_icon,
        }),
      );
      dispatch(
        updateByChatId({
          chat_id: currentConversationData.chat_id,
          group_icon: updateGroupProfile.data.group_icon,
        }),
      );
    }
  };

  async function updateGroupName() {
    const updateGroupProfile: UpdateGroupRes = await postData(
      "chat/update-group",
      {
        chat_id: currentConversationData.chat_id,
        group_name: group_name,
      },
      "multipart/form-data",
    );

    if (updateGroupProfile.status == true) {
      toast.success("Group Name Updated", { position: "top-right" });
      dispatch(
        updateCurrentConversation({
          group_name: updateGroupProfile.data.group_name,
        }),
      );
      dispatch(
        updateByChatId({
          chat_id: currentConversationData.chat_id,
          group_name: updateGroupProfile.data.group_name,
        }),
      );
    }
  }

  return (
    <>
      <div
        className="relative mb-4 h-80 w-full  bg-no-repeat "
        style={{
          backgroundImage: "url('/Home/profile_bg.png')",
          backgroundSize: "100%",
        }}
      >
        {/* Theme tint overlay (preserves transparency) */}
        <div
          className="absolute inset-0"
          style={{
            background: "var(--theme-color)",
            maskImage: "url('/Home/profile_bg.png')",
            WebkitMaskImage: "url('/Home/profile_bg.png')",
            maskSize: "100%",
            WebkitMaskSize: "100%",
            maskRepeat: "no-repeat",
            WebkitMaskRepeat: "no-repeat",
            opacity: 1,
            pointerEvents: "none",
          }}
        ></div>

        {/* Main content */}
        {/* <div className="relative z-10 flex items-center gap-3 px-3 pt-16 font-semibold text-black 2xl:pt-16">
    <div className="py-1"></div>
  </div> */}

        {/* Profile Section */}
        <div className="relative z-10 grid place-content-center  mt-12 pt-12 gap-y-2 text-center">
          <div className="mx-auto h-36 w-36 rounded-full bg-primary p-2">
            <div className="relative">
              <LoadingSkeletonImageDynamic
                radius=""
                className={`mx-auto min-h-32 min-w-32 cursor-pointer rounded-full bg-secondary object-cover`}
                image_height=""
                image_url={
                  currentConversationData.chat_type == "group"
                    ? selectedFileUrl || currentConversationData.group_icon!
                    : currentConversationData.profile_pic!
                }
                image_width=""
                onClickFunc={() => {
                  dispatch(
                    setViewImage({
                      show_image: true,
                      image_src: [
                        currentConversationData.chat_type == "group"
                          ? currentConversationData.group_icon!
                          : currentConversationData.profile_pic!,
                      ],
                    }),
                  );
                }}
              />

              {OnlineUserList.onlineUsers.find(
                (user) => user.user_id == currentConversationData.user_id,
              ) && (
                  <img
                    className="absolute bottom-2 right-2 h-5 w-5"
                    src="/Home/Online_Green_dot.png"
                    alt="online"
                  />
                )}

              <input
                onChange={onFileChange}
                accept="image/*"
                className="hidden"
                type="file"
                id="groupPhotoEdit"
              />

              {currentConversationData.chat_type == "group" && (
                <label
                  htmlFor="groupPhotoEdit"
                  className="absolute bottom-0 right-0 z-30 grid h-8 w-8 cursor-pointer place-content-center rounded-full bg-primary"
                >
                  <BiEditAlt className="primary-gradient rounded-full p-1 text-2xl" />
                </label>
              )}
            </div>
          </div>

          {/* Name + Edit */}
          <div className="relative flex">
            <input
              onChange={(e) => setGroup_name(e.target.value)}
              disabled={!editGroup}
              type="text"
              className={`w-fit max-w-72 bg-transparent text-center text-lg font-medium outline-none ${editGroup ? "border-b-2 border-borderColor px-2" : ""
                }`}
              value={
                currentConversationData.chat_type == "group"
                  ? group_name
                  : (ContactList?.data?.find(
                    (e: ContactType) =>
                      e?.user_id == currentConversationData.user_id,
                  )?.name ?? currentConversationData.full_name)
              }
            />

            {currentConversationData.chat_type == "group" && (
              <div className="absolute -right-7 top-0">
                {editGroup ? (
                  <MdCheck
                    onClick={() => {
                      setEditGroup(false);
                      updateGroupName();
                    }}
                    title="Save Group Name"
                    className="h-7 w-7 cursor-pointer p-1"
                  />
                ) : (
                  <BiEditAlt
                    onClick={() => setEditGroup(true)}
                    title="Edit Group Name"
                    className="h-7 w-7 cursor-pointer p-1"
                  />
                )}
              </div>
            )}
          </div>

          {/* Info Section */}
          <span className="flex items-center justify-center gap-2 font-sans text-sm font-medium text-[#808080]">
            {currentConversationData.chat_type == "group" ? (
              <>
                <TextTranslate text="Group" /> <GoDotFill />{" "}
                {GroupMemberData?.data?.Records?.length}{" "}
                <TextTranslate text="Members" />
              </>
            ) : (
              <>
                {
                  GroupMemberData?.data?.Records?.find(
                    (user) => user.user_id == currentConversationData.user_id,
                  )?.User?.country_code
                }{" "}
                {
                  GroupMemberData?.data?.Records?.find(
                    (user) => user.user_id == currentConversationData.user_id,
                  )?.User?.mobile_num
                }
              </>
            )}
          </span>
        </div>
      </div>

    </>
  );
}
