import { FC, useState } from "react";
import { CloseCircle } from "iconsax-react";
import { useTranslation } from "react-i18next";
import SwitchComponent from "../../../../components/Switch";
import Select from "../../../../components/Select";
import { useGetUsers } from "../../../users/hooks/useUserData";
import { UserItemType } from "../../../users/types/UserTypes";
import WorkspaceColorPicker from "./WorkspaceColorPicker";
import UserAvatar from "../../components/UserAvatar";

export type SelectedUser = {
  id: string;
  name: string;
  profilePic?: string;
};

type Props = {
  isActive: boolean;
  onIsActiveChange: (value: boolean) => void;
  selectedColor: string;
  onColorChange: (color: string) => void;
  selectedUsers: SelectedUser[];
  onSelectedUsersChange: (users: SelectedUser[]) => void;
};

const CreateWorkspaceSidebar: FC<Props> = ({
  isActive,
  onIsActiveChange,
  selectedColor,
  onColorChange,
  selectedUsers,
  onSelectedUsersChange,
}) => {
  const { t } = useTranslation("global");
  const getUsers = useGetUsers("");
  const [userSelectValue, setUserSelectValue] = useState("");

  const userItems =
    getUsers.data?.data?.users
      ?.filter(
        (user: UserItemType) =>
          !selectedUsers.some((selected) => selected.id === user.id),
      )
      .map((user: UserItemType) => ({
        label: `${user.firstName} ${user.lastName}`,
        value: user.id,
      })) ?? [];

  const handleUserSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    if (!value) return;

    const user = getUsers.data?.data?.users?.find(
      (item: UserItemType) => item.id === value,
    );

    if (user) {
      onSelectedUsersChange([
        ...selectedUsers,
        {
          id: user.id,
          name: `${user.firstName} ${user.lastName}`,
          profilePic: user.profilePic,
        },
      ]);
    }

    setUserSelectValue("");
  };

  const handleRemoveUser = (id: string) => {
    onSelectedUsersChange(selectedUsers.filter((user) => user.id !== id));
  };

  return (
    <div className="bg-white mt-10 w-sidebar text-xs hidden 2xl:block h-fit px-5 py-7 rounded-3xl">
      <div className="text-sm flex items-center justify-between">
        <div>{t("taskmanager.workspace_status")}</div>
        <div className="flex gap-2 text-xs items-center text-description">
          <div>{isActive ? t("slider.active") : t("slider.inactive")}</div>
          <SwitchComponent active={isActive} onChange={onIsActiveChange} />
        </div>
      </div>

      <div className="mt-8">
        <div className="text-sm">{t("taskmanager.choose_color")}</div>
        <div className="mt-3">
          <WorkspaceColorPicker
            selectedColor={selectedColor}
            onChange={onColorChange}
          />
        </div>
      </div>

      <div className="mt-8">
        <Select
          label={t("taskmanager.users")}
          placeholder={t("taskmanager.select_user")}
          items={userItems}
          value={userSelectValue}
          onChange={handleUserSelect}
          className="border"
        />

        <div className="mt-3 border border-dashed border-border rounded-xl p-4 flex gap-2 flex-wrap min-h-[52px]">
          {selectedUsers.length === 0 ? (
            <div className="text-description w-full text-center">
              {t("taskmanager.no_users_added")}
            </div>
          ) : (
            selectedUsers.map((user) => (
            <div
              key={user.id}
              className="bg-[#EBEEF5] flex gap-2 text-xs items-center px-2 py-2 rounded-lg"
            >
              <UserAvatar src={user.profilePic} alt={user.name} />
              <div>{user.name}</div>
              <CloseCircle
                variant="Bold"
                className="size-4 cursor-pointer"
                color="red"
                onClick={() => handleRemoveUser(user.id)}
              />
            </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
};

export default CreateWorkspaceSidebar;
