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

interface IDeleteContractModal {
  handleCancel: () => any;
  id: string;
  isOpen: boolean;
}

export const DeleteContractModal: FC<IDeleteContractModal> = ({
  handleCancel,
  id,
  isOpen,
}) => {
  const { id: orgID, contracts } = useStoreState((state) => state.organization);

  const { removeContract } = useStoreActions((actions) => actions.organization);
  const { removeContractFromUser } = useStoreActions((actions) => actions.user);
  const { deleteProjectForContract } = useStoreActions(
    (actions) => actions.projects,
  );

  const deleteContract = async (contractID: string) => {
    const options = {
      orgID: orgID,
      contractID: contractID,
    };
    await apiCall("organization/removeContract", options, (response: any) => {
      // remove contract from current user (userDetails => contracts)
      // remove all projects from this contract for current user (userDetails => projects)
      removeContractFromUser(contractID);

      // remove project from deleted contract in "projects" store (proejcts)
      deleteProjectForContract(contractID);

      // remove contract from all users which used this contract (org => members)
      // remove all projects from deleted contract for all users (org => members)
      // remove contract from organization (org => contracts)
      removeContract(contractID);

      handleCancel();
    });
  };
  return (
    <Modal
      title={t(dictionary.confirmDelete)}
      handleClose={handleCancel}
      handleConfirm={() => deleteContract(id)}
      isOpen={isOpen}
      exitOnEsc={true}
      headerDivader={true}
      primaryVariant="danger"
      labels={{
        primary: t(dictionary.delete),
        secondary: t(dictionary.cancel),
      }}
    >
      <Aligment
        direction="column"
        align="flex-start"
        justify="flex-start"
        gap={16}
      >
        <Text>{t(dictionary.deleteContractHeader)}</Text>
        <DeleteElementFrame>
          {getContractName(id, contracts)}
        </DeleteElementFrame>
        <Text>{t(dictionary.doYouWantDeleteContract)}</Text>
      </Aligment>
    </Modal>
  );
};
