import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import { rolesApi } from "~/api/roles-api.service";
import { MultiSelect, type MultiSelectProps } from "~/components/multi-select";
import { APPROLE } from "~/types/enum";

export interface IRolesSelectProps extends Omit<MultiSelectProps, "options"> {
  showRoot?: boolean;
}

export default function RolesSelect({ showRoot, ...props }: IRolesSelectProps) {
  const { data, isLoading, error } = useQuery({
    queryKey: ["roles"],
    queryFn: async () => {
      const response = await rolesApi.index();

      return response.data;
    },
  });

  const list = useMemo(() => {
    interface Option {
      value: string;
      label: string;
    }

    return (
      (data as IRole[] | undefined)
        ?.filter((item: IRole) => showRoot || item.role_key !== APPROLE.ROOT)
        .map(
          (item: IRole): Option => ({
            value: String(item.id),
            label: item.role_name,
          })
        ) ?? []
    );
  }, [data, showRoot]);

  return (
    <MultiSelect variant="inverted" maxCount={3} options={list} {...props} />
  );
}
