import React, { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { useContactList } from "../../../store/api/useContactList";
import { RxCross2 } from "react-icons/rx";
import {
  addOrRemoveUserId,
  addUserId,
} from "../../../store/Slices/CreateGroupSlice";

export default function SelectedContact() {
  const CreateGroup = useAppSelector((state) => state.CreateGroup);
  const userData = useAppSelector((state) => state.userData);
  const { data: contactListUser } = useContactList();

  const dispatch = useAppDispatch();

  useEffect(() => {
    if (userData.user_id == 0) {
      return;
    }
    dispatch(
      addUserId({
        user_id: userData.user_id,
      }),
    );
  }, [userData]);

  return (
    <>
      {CreateGroup.user_id.length !== 0 && (
        <>
          <div className="flex min-h-28 items-start gap-2 overflow-hidden overflow-x-auto px-3 py-3 text-center lg:max-w-96 2xl:max-w-96">
            <div className="flex w-24 shrink-0 flex-col items-center gap-2 overflow-hidden">
              <div className="relative">
                <img
                  className="h-10 w-10 rounded-full object-cover xl:h-12 xl:w-12"
                  src={userData.profile_pic}
                  alt=""
                />
              </div>
              <div className="text-xs">You</div>
            </div>
            {contactListUser?.data
              ?.filter(
                (contact) =>
                  CreateGroup.user_id.includes(contact?.user_id) &&
                  contact?.user_id != userData.user_id,
              )
              .map((e) => {
                return (
                  <div
                    key={e.user_id}
                    className="flex w-24 shrink-0 flex-col items-center gap-2 overflow-hidden"
                  >
                    <div className="relative">
                      <img
                        className="h-10 w-10 rounded-full object-cover xl:h-12 xl:w-12"
                        src={e.profile_pic}
                        alt=""
                      />
                      {userData.user_id != e.user_id && (
                        <RxCross2
                          onClick={() => {
                            dispatch(
                              addOrRemoveUserId({
                                user_id: e.user_id,
                              }),
                            );
                          }}
                          className="absolute -right-2 -top-0 z-30 h-5 w-5 cursor-pointer rounded-full primary-gradient"
                        />
                      )}
                    </div>
                    <div className="text-xs">
                      {userData.user_id == e.user_id ? "You" : e?.name}
                    </div>
                  </div>
                );
              })}
          </div>
        </>
      )}
    </>
  );
}
