import { type FC } from "react";
import { useTranslation } from "react-i18next";
import Input from "../../../../../components/Input";
import UserAvatar from "../../UserAvatar";
import TaskDetailLabelCheckbox from "../labels/TaskDetailLabelCheckbox";
import type { TaskUser } from "./types";

type Props = {
  users: TaskUser[];
  selectedIds: Set<string>;
  onToggle: (id: string) => void;
  isLoading?: boolean;
  isSubmitting?: boolean;
  hasNextPage?: boolean;
  isFetchingNextPage?: boolean;
  onLoadMore?: () => void;
  search: string;
  onSearchChange: (value: string) => void;
};

const TaskDetailUsersList: FC<Props> = ({
  users,
  selectedIds,
  onToggle,
  isLoading = false,
  isSubmitting = false,
  hasNextPage = false,
  isFetchingNextPage = false,
  onLoadMore,
  search,
  onSearchChange,
}) => {
  const { t } = useTranslation("global");

  const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const target = event.currentTarget;
    const isNearBottom = target.scrollHeight - target.scrollTop - target.clientHeight < 80;

    if (isNearBottom && hasNextPage && !isFetchingNextPage) {
      onLoadMore?.();
    }
  };

  return (
    <div className="flex flex-col gap-3">
      <div>
        <h3 className="text-xs font-bold text-center">{t("taskmanager.users")}</h3>
      </div>

      <Input
        label={t("search")}
        value={search}
        onChange={(e) => onSearchChange(e.target.value)}
        className="h-8 bg-white/63 border-white"
        labelClassName="text-xs"
      />

      <div>
        <div className="text-xs font-medium mb-2">{t("taskmanager.task_detail.members")}</div>

        {isLoading ? (
          <div className="text-[10px] text-description text-center py-2">{t("loading")}</div>
        ) : (
          <div className="flex flex-col gap-2 max-h-48 overflow-y-auto" onScroll={handleScroll}>
            {users.map((user) => {
              const isSelected = selectedIds.has(user.id);

              return (
                <div key={user.id} className="flex gap-1.5 items-center">
                  <TaskDetailLabelCheckbox
                    checked={isSelected}
                    onToggle={() => onToggle(user.id)}
                    ariaLabel={user.name}
                  />
                  <UserAvatar src={user.avatar} alt={user.name} />
                  <div className="text-[10px]">{user.name}</div>
                </div>
              );
            })}
            {isFetchingNextPage ? <div className="text-[10px] text-description text-center py-1">{t("loading")}</div> : null}
            {!users.length ? <div className="text-[10px] text-description">{t("taskmanager.no_users_added")}</div> : null}
          </div>
        )}
      </div>

      {isSubmitting ? <div className="text-[10px] text-description text-center">{t("loading")}</div> : null}
    </div>
  );
};

export default TaskDetailUsersList;
