import { CloseCircle, Gallery } from "iconsax-react";
import { FC, useRef, useState } from "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 { useGetWorkspaces } from "../../workspace/hooks/useWorkspaceData";
import { WorkspaceItemType } from "../../workspace/types/WorkspaceTypes";
import WorkspaceColorPicker from "../../workspace/components/WorkspaceColorPicker";
import UserAvatar from "../../components/UserAvatar";

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

export 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)",
] as const;

export const getPresetPrimaryColor = (preset: string) =>
  preset.match(/#[0-9a-fA-F]{6}/)?.[0] ?? "#A8E6CF";

export const findMatchingBackgroundPreset = (color: string) =>
  BACKGROUND_PRESETS.find(
    (preset) => getPresetPrimaryColor(preset).toLowerCase() === color.toLowerCase(),
  ) ?? null;

type Props = {
  isActive: boolean;
  onIsActiveChange: (value: boolean) => void;
  selectedColor: string;
  onColorChange: (color: string) => void;
  selectedUsers: SelectedUser[];
  onSelectedUsersChange: (users: SelectedUser[]) => void;
  selectedBackground: string | null;
  onBackgroundChange: (background: string | null) => void;
  backgroundImage: File | null;
  onBackgroundImageChange: (file: File | null) => void;
  workspaceId: string;
  onWorkspaceIdChange: (id: string) => void;
  workspaceError?: string;
  className?: string;
};

const CreateProjectSidebar: FC<Props> = ({
  isActive,
  onIsActiveChange,
  selectedColor,
  onColorChange,
  selectedUsers,
  onSelectedUsersChange,
  selectedBackground,
  onBackgroundChange,
  backgroundImage,
  onBackgroundImageChange,
  workspaceId,
  onWorkspaceIdChange,
  workspaceError,
  className,
}) => {
  const { t } = useTranslation("global");
  const getUsers = useGetUsers("");
  const getWorkspaces = useGetWorkspaces();
  const [userSelectValue, setUserSelectValue] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  const workspaces: WorkspaceItemType[] =
    getWorkspaces.data?.data?.workspaces ??
    getWorkspaces.data?.data ??
    [];

  const workspaceItems = workspaces.map((workspace) => ({
    label: workspace.name,
    value: workspace.id,
  }));

  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));
  };

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

  return (
    <div
      className={
        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={onIsActiveChange} />
        </div>
      </div>

      <div className="mt-8">
        <Select
          label={t("taskmanager.workspacename")}
          placeholder={t("taskmanager.select_workspace")}
          items={workspaceItems}
          value={workspaceId}
          onChange={(e) => onWorkspaceIdChange(e.target.value)}
          className="border"
          error_text={workspaceError ?? ""}
        />
      </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 className="mt-8">
        <div className="text-sm mb-3">{t("taskmanager.background")}</div>
        <div className="flex flex-wrap gap-2">
          {BACKGROUND_PRESETS.map((background) => (
            <button
              key={background}
              type="button"
              className="w-20 h-10 border"
              style={{
                background,
                borderColor: selectedBackground === background ? "#000" : "#E2E8F0",
              }}
              onClick={() => {
                onBackgroundChange(background);
                onColorChange(getPresetPrimaryColor(background));
              }}
            />
          ))}
        </div>
      </div>

      <div className="mt-8">
        <div className="text-sm mb-3">{t("taskmanager.choose_color")}</div>
        <WorkspaceColorPicker
          selectedColor={selectedColor}
          onChange={(color) => {
            onBackgroundChange(findMatchingBackgroundPreset(color));
            onColorChange(color);
          }}
        />
      </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;
