import { CloseCircle, TickCircle } from "iconsax-react";
import { type FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from '../../../../components/Toast';
import Button from "../../../../components/Button";
import { ErrorType } from "../../../../helpers/types";
import { clx } from "../../../../helpers/utils";
import { useSingleUpload } from "../../../service/hooks/useServiceData";
import { useUpdateProject } from "../hooks/useProjectData";
import type { ProjectDetailType } from "../types/ProjectTypes";
import CreateProjectSidebar, {
  findMatchingBackgroundPreset,
  type SelectedUser,
} from "./CreateProjectSidebar";

type Props = {
  open: boolean;
  onClose: () => void;
  projectId: string;
  project?: ProjectDetailType;
};

const ProjectSettingsPanel: FC<Props> = ({ open, onClose, projectId, project }) => {
  const { t } = useTranslation("global");
  const queryClient = useQueryClient();
  const updateProject = useUpdateProject();
  const singleUpload = useSingleUpload();

  const [isActive, setIsActive] = useState(true);
  const [selectedColor, setSelectedColor] = useState("#A8E6CF");
  const [selectedUsers, setSelectedUsers] = useState<SelectedUser[]>([]);
  const [selectedBackground, setSelectedBackground] = useState<string | null>(null);
  const [backgroundImage, setBackgroundImage] = useState<File | null>(null);
  const [workspaceId, setWorkspaceId] = useState("");
  const [existingBackgroundPicture, setExistingBackgroundPicture] = useState("");

  useEffect(() => {
    if (!open) {
      document.body.style.overflow = "auto";
      return;
    }

    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "auto";
    };
  }, [open]);

  useEffect(() => {
    if (!open || !project) return;

    const backgroundColor = project.backgroundColor ?? "#A8E6CF";
    setIsActive(project.isActive);
    setSelectedBackground(findMatchingBackgroundPreset(backgroundColor));
    setSelectedColor(backgroundColor);
    setWorkspaceId(project.workspaceId);
    setExistingBackgroundPicture(project.backgroundPicture ?? "");
    setBackgroundImage(null);

    if (project.users?.length) {
      setSelectedUsers(
        project.users.map((user) => ({
          id: user.id,
          name: `${user.firstName} ${user.lastName}`,
          profilePic: user.profilePic,
        })),
      );
    } else if (project.userIds?.length) {
      setSelectedUsers(
        project.userIds.map((userId) => ({
          id: userId,
          name: userId,
        })),
      );
    } else {
      setSelectedUsers([]);
    }
  }, [open, project]);

  const handleSave = async () => {
    if (!project) return;

    if (!workspaceId) {
      toast(t("taskmanager.select_workspace"), 'error');
      return;
    }

    let backgroundPicture = existingBackgroundPicture;

    if (backgroundImage) {
      const formData = new FormData();
      formData.append("file", backgroundImage);

      try {
        const uploadResult = await singleUpload.mutateAsync(formData);
        backgroundPicture = uploadResult?.data?.url ?? "";
      } catch (error) {
        const uploadError = error as ErrorType;
        toast(uploadError.response?.data?.error.message[0], 'error');
        return;
      }
    }

    updateProject.mutate(
      {
        id: projectId,
        params: {
          name: project.name,
          ownerName: project.ownerName,
          description: project.description ?? "",
          startDate: project.startDate,
          backgroundPicture,
          backgroundColor: selectedColor,
          isActive,
          workspaceId,
          userIds: selectedUsers.map((user) => user.id),
        },
      },
      {
        onSuccess: () => {
          toast(t("success"), 'success');
          queryClient.invalidateQueries({ queryKey: ["project", projectId] });
          queryClient.invalidateQueries({ queryKey: ["project-detail", projectId] });
          onClose();
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], 'error');
        },
      },
    );
  };

  if (!open) return null;

  return (
    <>
      <div
        className="fixed inset-0 z-[70] bg-black/40"
        onClick={onClose}
        aria-hidden
      />

      <div
        className={clx(
          "fixed top-0 bottom-0 left-0 z-[80] w-full max-w-[320px] bg-white shadow-xl flex flex-col transition-transform duration-300 ease-in-out",
          open ? "translate-x-0" : "-translate-x-full",
        )}
      >
        <div className="flex items-center justify-between px-5 py-4 border-b border-border shrink-0">
          <div className="text-sm font-bold">{t("taskmanager.project_settings")}</div>
          <button type="button" onClick={onClose} className="p-1">
            <CloseCircle size={22} color="#8C90A3" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-5 py-6">
          <CreateProjectSidebar
            className="w-full text-xs block h-fit p-0 rounded-none"
            isActive={isActive}
            onIsActiveChange={setIsActive}
            selectedColor={selectedColor}
            onColorChange={setSelectedColor}
            selectedUsers={selectedUsers}
            onSelectedUsersChange={setSelectedUsers}
            selectedBackground={selectedBackground}
            onBackgroundChange={setSelectedBackground}
            backgroundImage={backgroundImage}
            onBackgroundImageChange={setBackgroundImage}
            workspaceId={workspaceId}
            onWorkspaceIdChange={setWorkspaceId}
          />
        </div>

        <div className="px-5 py-4 border-t border-border shrink-0">
          <Button
            className="w-full"
            isLoading={updateProject.isPending || singleUpload.isPending}
            onClick={handleSave}
          >
            <div className="flex gap-2 justify-center">
              <TickCircle className="size-5" color="#fff" />
              <div>{t("submit")}</div>
            </div>
          </Button>
        </div>
      </div>
    </>
  );
};

export default ProjectSettingsPanel;
