// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import Grid from "@mui/material/Grid";
import { Box, Button, LinearProgress } from "@mui/material";
import { Theme } from "@mui/material/styles";
import createStyles from "@mui/styles/createStyles";
import withStyles from "@mui/styles/withStyles";
import {
  modalStyleUtils,
  serviceAccountStyles,
} from "../Common/FormComponents/common/styleLibrary";
import { NewServiceAccount } from "../Common/CredentialsPrompt/types";
import { setModalErrorSnackMessage } from "../../../actions";
import { ErrorResponseHandler } from "../../../common/types";
import ModalWrapper from "../Common/ModalWrapper/ModalWrapper";
import api from "../../../common/api";
import CodeMirrorWrapper from "../Common/FormComponents/CodeMirrorWrapper/CodeMirrorWrapper";
import FormSwitchWrapper from "../Common/FormComponents/FormSwitchWrapper/FormSwitchWrapper";
import InputBoxWrapper from "../Common/FormComponents/InputBoxWrapper/InputBoxWrapper";
import { AccountIcon } from "../../../icons";

const styles = (theme: Theme) =>
  createStyles({
    ...serviceAccountStyles,
    ...modalStyleUtils,
  });

interface IAddServiceAccountProps {
  classes: any;
  open: boolean;
  closeModalAndRefresh: (res: NewServiceAccount | null) => void;
  setModalErrorSnackMessage: typeof setModalErrorSnackMessage;
}

const AddServiceAccount = ({
  classes,
  open,
  closeModalAndRefresh,
  setModalErrorSnackMessage,
}: IAddServiceAccountProps) => {
  const [addSending, setAddSending] = useState<boolean>(false);
  const [policyDefinition, setPolicyDefinition] = useState<string>("");
  const [accessKey, setAccessKey] = useState<string>("");
  const [secretKey, setSecretKey] = useState<string>("");
  const [isRestrictedByPolicy, setIsRestrictedByPolicy] =
    useState<boolean>(false);
  const [addCredentials, setAddCredentials] = useState<boolean>(false);

  useEffect(() => {
    if (addSending) {
      if (addCredentials) {
        api
          .invoke("POST", `/api/v1/service-account-credentials`, {
            policy: policyDefinition,
            accessKey: accessKey,
            secretKey: secretKey,
          })
          .then((res) => {
            setAddSending(false);
            closeModalAndRefresh(res);
          })
          .catch((err: ErrorResponseHandler) => {
            setAddSending(false);
            setModalErrorSnackMessage(err);
          });
      } else {
        api
          .invoke("POST", `/api/v1/service-accounts`, {
            policy: policyDefinition,
          })
          .then((res) => {
            setAddSending(false);
            closeModalAndRefresh(res);
          })
          .catch((err: ErrorResponseHandler) => {
            setAddSending(false);
            setModalErrorSnackMessage(err);
          });
      }
    }
  }, [
    addSending,
    setAddSending,
    setModalErrorSnackMessage,
    policyDefinition,
    closeModalAndRefresh,
    addCredentials,
    accessKey,
    secretKey,
  ]);

  const addServiceAccount = (e: React.FormEvent) => {
    e.preventDefault();
    setAddSending(true);
  };

  const resetForm = () => {
    setPolicyDefinition("");
  };

  return (
    <ModalWrapper
      modalOpen={open}
      onClose={() => {
        closeModalAndRefresh(null);
      }}
      title={`创建服务账号`}
      titleIcon={<AccountIcon />}
    >
      <form
        noValidate
        autoComplete="off"
        onSubmit={(e: React.FormEvent<HTMLFormElement>) => {
          addServiceAccount(e);
        }}
      >
        {addSending && (
          <Grid item xs={12}>
            <LinearProgress />
          </Grid>
        )}
        <Grid container className={classes.modalFormScrollable}>
          <Grid item xs={12}>
            <div className={classes.infoDetails}>
            服务帐户继承显式附加到父用户的策略，以及附加到父用户具有成员资格的每个组的策略。您可以在下面指定一个可选的JSON格式策略，以将服务帐户访问限制为父用户明确允许的操作和资源的子集。
              <Box sx={{ paddingTop: "15px", paddingBottom: "15px" }}>
              保存后不能修改服务帐户可选策略。
              </Box>
            </div>
          </Grid>
          <Grid item xs={12}>
            <Grid item xs={12}>
              <FormSwitchWrapper
                value="locking"
                id="locking"
                name="locking"
                checked={addCredentials}
                onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                  setAddCredentials(event.target.checked);
                }}
                label={"自定义凭据"}
              />
              {addCredentials && (
                <Grid item xs={12}>
                  <div className={classes.stackedInputs}>
                    <InputBoxWrapper
                      value={accessKey}
                      label={"访问密钥"}
                      id={"accessKey"}
                      name={"accessKey"}
                      placeholder={"输入访问密钥"}
                      onChange={(e) => {
                        setAccessKey(e.target.value);
                      }}
                    />
                    <InputBoxWrapper
                      value={secretKey}
                      label={"密钥"}
                      id={"secretKey"}
                      name={"secretKey"}
                      placeholder={"输入秘钥"}
                      onChange={(e) => {
                        setSecretKey(e.target.value);
                      }}
                    />
                  </div>
                </Grid>
              )}
            </Grid>
            <Grid item xs={12}>
              <FormSwitchWrapper
                value="locking"
                id="locking"
                name="locking"
                checked={isRestrictedByPolicy}
                onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                  setIsRestrictedByPolicy(event.target.checked);
                }}
                label={"策略限制"}
              />
              {isRestrictedByPolicy && (
                <Grid item xs={12} className={classes.codeMirrorContainer}>
                  <CodeMirrorWrapper
                    label={"策略 "}
                    value={policyDefinition}
                    onBeforeChange={(editor, data, value) => {
                      setPolicyDefinition(value);
                    }}
                  />
                </Grid>
              )}
            </Grid>
          </Grid>
        </Grid>
        <Grid container>
          <Grid item xs={12} className={classes.modalButtonBar}>
            <Button
              type="button"
              color="primary"
              variant="outlined"
              onClick={resetForm}
            >
              清除
            </Button>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              disabled={addSending}
            >
              创建
            </Button>
          </Grid>
        </Grid>
      </form>
    </ModalWrapper>
  );
};

const mapDispatchToProps = {
  setModalErrorSnackMessage,
};

const connector = connect(null, mapDispatchToProps);

export default withStyles(styles)(connector(AddServiceAccount));
