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

type SelectedUser = {
  id: string;
  name: string;
};

const BACKGROUND_PRESETS = [
  "linear-gradient(45deg, #6a11cb, #2575fc)",
  "linear-gradient(45deg, #ff00cc, #333399)",
  "linear-gradient(45deg, #ff0000, #ff8c00)",
  "linear-gradient(45deg, #3f2b96, #a8c0ff)",
  "linear-gradient(45deg, #7f7fd5, #91eae4)",
  "linear-gradient(45deg, #2c3e50, #4ca1af)",
  "linear-gradient(45deg, #1cb5e0, #000851)",
  "linear-gradient(45deg, #0052d4, #4364f7)",
] as const;

const CreateProjectSidebar: FC = () => {
  const { t } = useTranslation("global");
  const getUsers = useGetUsers("");

  const [isActive, setIsActive] = useState(true);
  const [selectedColor, setSelectedColor] = useState("#A8E6CF");
  const [selectedUsers, setSelectedUsers] = useState<SelectedUser[]>([]);
  const [userSelectValue, setUserSelectValue] = useState("");
  const [selectedBackground, setSelectedBackground] = useState<string>(
    BACKGROUND_PRESETS[0],
  );
  const [backgroundImage, setBackgroundImage] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  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) {
      setSelectedUsers((prev) => [
        ...prev,
        { id: user.id, name: `${user.firstName} ${user.lastName}` },
      ]);
    }

    setUserSelectValue("");
  };

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

  const handleBackgroundImageChange = (
    event: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const file = event.target.files?.[0] ?? null;
    setBackgroundImage(file);
  };

  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.project_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={setIsActive} />
        </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"
              >
                <div>{user.name}</div>
                <CloseCircle
                  variant="Bold"
                  className="size-4 cursor-pointer"
                  color="red"
                  onClick={() => handleRemoveUser(user.id)}
                />
              </div>
            ))
          )}
        </div>
      </div>

      <div className="mt-8">
        <div className="text-sm mb-3">{t("taskmanager.background")}</div>
        <div className="grid grid-cols-4 gap-2">
          {BACKGROUND_PRESETS.map((background) => (
            <button
              key={background}
              type="button"
              className="h-8 rounded-md border"
              style={{
                background,
                borderColor:
                  selectedBackground === background ? "#000" : "#E2E8F0",
              }}
              onClick={() => setSelectedBackground(background)}
            />
          ))}
        </div>
      </div>

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

      <div className="mt-8">
        <div className="text-sm mb-3">{t("taskmanager.background_image")}</div>
        <button
          type="button"
          onClick={() => fileInputRef.current?.click()}
          className="w-full min-h-[112px] border border-dashed border-border rounded-xl flex flex-col items-center justify-center text-description px-4"
        >
          <Gallery size={26} color="#8C90A3" />
          <div className="mt-2 text-xs text-center">
            {backgroundImage
              ? backgroundImage.name
              : t("taskmanager.upload_background")}
          </div>
        </button>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={handleBackgroundImageChange}
        />
      </div>
    </div>
  );
};

export default CreateProjectSidebar;
