import { useNavigate } from "react-router-dom";
import { useAppSelector } from "../../../utils/hooks";
import useApiPost from "../../../hooks/PostData";
import { useFile } from "../../../context/FileProvider";
import { CreateGroupRes } from "../../../types/ResType";
import toast from "react-hot-toast";
import { ClipLoader } from "react-spinners";
import { useTheme } from "../../../context/ThemeProvider";
import { useQueryClient } from "react-query";

export default function DoneButton() {
  const CreateGroup = useAppSelector((state) => state.CreateGroup);
  const userData = useAppSelector((state) => state.userData);
  const navigate = useNavigate();
  const { loading, postData } = useApiPost();
  const { selectedFile } = useFile();
  const { theme } = useTheme();
  const queryClient = useQueryClient();

  if (CreateGroup.user_id.length === 0) return null;

  async function createGroupApi() {
    // if (selectedFile == null) {
    //   return toast.error("Please Select Group Profile!", {
    //     position: "bottom-left",
    //   });
    // }
    if (
      CreateGroup.group_name == "Group Name" ||
      CreateGroup.group_name == ""
    ) {
      return toast.error("Please Enter Group Name!", {
        position: "bottom-left",
      });
    }

    const createGroupFormData = new FormData();

    createGroupFormData.append("group_name", CreateGroup.group_name);
    createGroupFormData.append("group_icon", selectedFile!);
    createGroupFormData.append("pictureType", "group_icon");
    createGroupFormData.append(
      "group_description",
      CreateGroup.group_description,
    );

    CreateGroup.user_id.forEach((user_id: string) => {
      if (user_id != userData.user_id.toString()) {
        createGroupFormData.append("participants", user_id.toString());
      }
    });

    // Make the API call with the constructed FormData
    const createGroupResponse: CreateGroupRes = await postData(
      "chat/create-group",
      createGroupFormData,
      "multipart/form-data",
    );

    toast.success("Group Created Successfully");
    // Remove all pages for a specific chatId from cacheData
    // queryClient.invalidateQueries(["message_list", createGroupResponse.data.chat_id]);
    navigate("/chat");
  }

  return (
    <div className="absolute bottom-10 flex h-24 w-full items-end bg-gradient-to-t from-primary to-transparent lg:bottom-0">
      <div
        onClick={() => {
          createGroupApi();
        }}
        className="primary-gradient mx-auto my-5 w-[90%] cursor-pointer rounded-lg py-2 text-center"
      >
        {loading ? (
          <ClipLoader size={17} color={theme == "dark" ? "white" : "black"} />
        ) : (
          "Done"
        )}
      </div>
    </div>
  );
}
