"use client";

import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useRouter } from "next/navigation";

import styles from "@/components/administrator/UserData/userdata.module.css";

import Loader from "@/components/web/Loader/loader";
import Table from "@/components/administrator/Table/table";
import NewUser from "../NewUser/new.user";

import { useSearch } from "@/hooks/useSearch";
import { useUser } from "@/hooks/useUser";
import { searchUser } from "@/services/users";

import { FiSearch } from "react-icons/fi";
import { IoCloseOutline } from "react-icons/io5";

/**
 * @type {React.FC <{
 *     initialData: any[];
 *     limit: number;
 *     sort: object;
 * }>}
 * @returns
 */
const UsersData = (props) => {
  const searchref = useRef(null);
  const router = useRouter();

  const [users, setUsers] = useState(props.initialData);
  const [selected, setSelected] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const { deleteMultipleUser, disableUser, enableUser } = useUser();

  const usersData = useMemo(
    () =>
      users.map((user) => ({
        ...user,
        status: user?.status ? user.status : !user?.status,
        disabling: (() => {
          if (typeof user?.status === "boolean")
            return user?.status ? "Disable" : "Enable";
          else return "Disable";
        })(),
      })),
    [users]
  );

  const {
    isLoading: loadSearch,
    isSearch,
    handleInput,
    handleSubmit,
    setInitialData,
    setSearchFn,
    setSetDataFn,
    cancel,
  } = useSearch();

  const setData = useCallback((data) => {
    setUsers(data);
  }, []);

  useEffect(() => {
    setIsLoading(loadSearch);
  }, [loadSearch]);

  return (
    <div className={styles.post_container}>
      <div className={styles.post_header}>
        <div className={styles.header_wrapper}>
          <h1>User Management</h1>
          <div className={styles.post_action}>
            {selected.length > 0 && (
              <div className={styles.post_status}>
                <p>
                  Selected:{" "}
                  <span>
                    {selected.length} item{selected.length > 1 && "s"}
                  </span>{" "}
                </p>
                <p>
                  <span
                    className={styles.action}
                    onClick={async () => {
                      deleteMultipleUser(
                        selected.map((item) => item._id),
                        (result) => {
                          const deletedId = result.map((item) => item._id);
                          setUsers((prev) =>
                            prev.filter((item) => !deletedId.includes(item._id))
                          );
                          setSelected([]);
                        }
                      );
                    }}>
                    Delete item{selected.length > 1 && "s"}
                  </span>{" "}
                </p>
              </div>
            )}
            <NewUser
              className={styles.post_button}
              getUser={(result) => {
                setUsers((prev) => [...prev, result]);
              }}>
              Add User
            </NewUser>
          </div>
        </div>
        <div className={styles.header_wrapper}>
          <form
            className={styles.search_container}
            onSubmit={handleSubmit}>
            <FiSearch />
            <input
              type="text"
              ref={searchref}
              placeholder="Search User"
              onInput={handleInput}
              onFocus={() => {
                if (!isSearch) setInitialData(users);

                setSearchFn(searchUser);
                setSetDataFn(setData);
              }}
            />
            {isSearch && (
              <IoCloseOutline
                onClick={() => {
                  searchref.current.value = "";
                  cancel();
                }}
                style={{ cursor: "pointer" }}
              />
            )}
          </form>
        </div>
      </div>
      {isLoading ? (
        <div className={styles.loader_container}>
          <div className={styles.loader}>
            <Loader
              color="#000"
              width={30}
            />
            <p>Getting data</p>
          </div>
        </div>
      ) : (
        <Table
          data={usersData}
          selected={selected}
          limit={props.limit}
          role={{
            name: "Name",
            username: "Username",
            role: "Role",
            disabling: "Action",
          }}
          style={{
            disabling: {
              width: "100px",
              textAlign: "center",
              textDecoration: "underline",
            },
          }}
          itemClick={{
            disabling: (realdata, data, event) => {
              const changeStatus = (status) => {
                setUsers((prev) =>
                  prev.map((user) =>
                    user._id === data._id ? { ...user, status } : user
                  )
                );
              };
              const action = {
                Disable: () =>
                  disableUser(data._id, (result) => changeStatus(false)),
                Enable: () =>
                  enableUser(data._id, (result) => changeStatus(true)),
              };

              return action[data.disabling]();
            },
          }}
          onClick={(data) => {
            router.push(`/dashboard/users/${data._id}`);
          }}
          onSelected={(data) => {
            setSelected(data);
          }}
        />
      )}
    </div>
  );
};

export default UsersData;
