import React, { FC } from "react";
import { Aligment, Modal, Text } from "venice-ui";
import { t } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { apiCall } from "../../untils/apiCall";
import { useStoreActions, useStoreState } from "../../store";
import { DeleteElementFrame } from "../components";

interface IDeleteProjectModalProps {
  handleCancel: () => any;
  id: string;
  name: string;
  isOpen: boolean;
  handleCancelWithAction?: () => any;
}

export const DeleteProjectModal: FC<IDeleteProjectModalProps> = ({
  handleCancel,
  name,
  id,
  isOpen,
  handleCancelWithAction,
}) => {
  const { id: orgID } = useStoreState((state) => state.organization);
  const { removeProjectFromUser } = useStoreActions((actions) => actions.user);
  const { removeProjectFromOrganization } = useStoreActions(
    (actions) => actions.organization,
  );
  const { deleteProject: deleteProjectsFromStore } = useStoreActions(
    (actions) => actions.projects,
  );

  const deleteProject = async (projectID: string) => {
    await apiCall(
      "projects/removeProject",
      {
        orgID,
        projectID,
      },
      (response: any) => {
        //remove proejct from userDetails => contracts => project
        removeProjectFromUser({ projectID });

        //remove project from organization => contracts => projects
        //remove project form access in organization => members => access
        removeProjectFromOrganization({ projectID });

        //remove project from projects => projects
        deleteProjectsFromStore({ projectID });
        if (handleCancelWithAction) {
          handleCancelWithAction();
        } else {
          handleCancel();
        }
      },
    );
  };

  return (
    <Modal
      title={t(dictionary.confirmDelete)}
      handleClose={handleCancel}
      handleConfirm={() => deleteProject(id)}
      headerDivader={true}
      isOpen={isOpen}
      exitOnEsc={true}
      labels={{
        primary: t(dictionary.delete),
        secondary: t(dictionary.cancel),
      }}
      primaryVariant="danger"

    >
      <Aligment
        direction="column"
        align="flex-start"
        justify="flex-start"
        gap={16}
      >
      <Text>{t(dictionary.deleteProjectHeader)}</Text>
      <DeleteElementFrame>{name}</DeleteElementFrame>
      <Text>{t(dictionary.doYouWantDeleteProject)}</Text>

      </Aligment>
    </Modal>
  );
};
