import React, { FC, useEffect, useState } from "react";
import { Aligment, Dropdown, Input, Modal, Text } from "venice-ui";
import { t } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { useStoreState } from "../../store";
import { IntputWrapperBig } from "../SingIn/Login.styles";
import { getMemberEmail } from "../../helpers/organizationHelper";
import { IOption } from "../../definitions/element";
import { MEMBER_ROLE } from "../../definitions/organizations";

interface IDeleteProjectModalProps {
  handleCancel: () => void;
  handleDelete: (newEmail?: string) => void;
  loader: boolean;
  userID: string;
  isOpen: boolean;
}

export const DeleteUserModal: FC<IDeleteProjectModalProps> = ({
  handleCancel,
  handleDelete,
  loader,
  userID,
  isOpen,
}) => {
  const { email, uid } = useStoreState((state) => state.user.userDetails);
  const { members, email: orgMail } = useStoreState(
    (state) => state.organization
  );

  const isSelf = uid === userID;
  const [needChange, setNeedChange] = useState(false);
  const [emailToCheck, setEmailToCheck] = useState("");

  useEffect(() => {
    setEmailToCheck(isSelf ? email : getMemberEmail(members, userID));
    const member = members.find(
      (_memeber) =>
        _memeber.id === userID && _memeber.role === MEMBER_ROLE.admin
    );
    if (orgMail === member?.email) {
      setNeedChange(true);
    }
  }, []);

  const [pageData, setPageData] = useState({
    email: "",
    newEmail: "",
  });

  const setEmailValue = (field: string, value: string) => {
    setPageData({
      ...pageData,
      [field]: value,
    });
  };

  const validation = () => {
    let error = false;
    if (pageData.email !== emailToCheck) {
      error = true;
    }
    if (needChange) {
      if (pageData.newEmail === "") {
        error = true;
      }
    }
    return error;
  };
  const onClose = () => {
    if (!loader) {
      handleCancel();
    }
  };
  const getMemebersScope = () => {
    const membersScope: IOption[] = [];
    members
      .filter((_member) => _member.id !== userID && _member.role === "admin")
      .forEach((_fm) => {
        membersScope.push({ value: _fm.id, label: _fm.email });
      });

    return membersScope;
  };

  const checkBeforeDelete = () => {
    let email = "";
    if (pageData.newEmail !== "") {
      email =
        members.find((_member) => _member.id === pageData.newEmail)?.email ||
        "";
    }
    handleDelete(email);
  };
  //ToDo check and clear
  return (
    <Modal
      title={t(dictionary.confirmDelete)}
      headerDivader={true}
      handleClose={onClose}
      handleConfirm={checkBeforeDelete}
      submitDisabled={validation()}
      submitLoader={loader}
      isOpen={isOpen}
      exitOnEsc={true}
      labels={{
        primary: t(dictionary.closeAccount),
        secondary: t(dictionary.cancel),
      }}
       primaryVariant="danger"
    >
      <Aligment gap={20}>
        <Text>
          {isSelf
            ? t(dictionary.doYouWantDeleteAccount)
            : t(dictionary.doYouWantDeleteUser)}
        </Text>
        <Text>
          {isSelf
            ? t(dictionary.confirmAccountDelete)
            : t(dictionary.confirmUserAccountDelete)}
        </Text>
        <IntputWrapperBig>
          <Input
            label={t(dictionary.enterEmailAddress)}
            type="text"
            labelPosition="top"
            value={pageData.email}
            name="login"
            handleChange={(name: string, value: string | number) =>
              setEmailValue("email", value as string)
            }
          />
        </IntputWrapperBig>
        {needChange && (
          <>
            <Text>{t(dictionary.orgMailNeedChange)}</Text>
            <IntputWrapperBig>
              <Dropdown
                zIndex={1001}
                options={[...getMemebersScope()]}
                value={pageData.newEmail}
                handleChange={(name: string, value: string | number) =>
                  setEmailValue(name, value as string)
                }
                name={"newEmail"}
              />
            </IntputWrapperBig>
          </>
        )}
      </Aligment>
    </Modal>
  );
};
