import { CustomModal } from 'dashboard/core/components/modal';
import { ModalContext } from 'dashboard/core/contexts/modals';
import { createIAMRole } from 'dashboard/core/utils/iam_role';
import { code } from 'dashboard/generated/controlplane';
import * as React from 'react';
import { useContext, useState } from 'react';
import {
  Button,
  ButtonType,
  Color,
  Column,
  CoreText,
  Display,
  FormGroup,
  FormGroupOrientation,
  Grid,
  Input,
  InputType,
  JustifyContent,
  Layout,
} from 'twitch-core-ui';

import twirp = code.justin.tv.eventbus.controlplane;

const iamRoleARNRegex = /^arn:aws:iam::\d{12}:role(\/[a-zA-Z0-9+=.@,_\-?]+)+$/; // the '?' isnt technically valid, but our 'backfill' used it, so support it for now. no one will use it, probably (https://jira.twitch.com/browse/ASYNC-830)

export function isInvalidARN(arn: string): boolean {
  return !RegExp(iamRoleARNRegex).test(arn);
}

const PLACEHOLDER_IAM_ROLE =
  'arn:aws:iam::123456789012:role/your-role-goes-here';
const PLACEHOLDER_IAM_ROLE_LABEL =
  'Alias for your IAM role (e.g. myservice-prod)';

interface Props {
  serviceID: string;
  onSuccess: (iamRole: twirp.IIAMRole) => void;
}

export const AddIAMRoleModal = ({ onSuccess, serviceID }: Props) => {
  const [label, setLabel] = useState('');
  const [arn, setArn] = useState('');
  const [errorText, setErrorText] = useState('');
  const { hideModal } = useContext(ModalContext);

  const handleArnChange = (
    e: React.FormEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => {
    setArn(e.currentTarget.value);
  };

  const handleLabelChange = (
    e: React.FormEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => {
    setLabel(e.currentTarget.value);
  };

  const handleIAMRoleSubmit = () => {
    createIAMRole(
      serviceID,
      {
        arn,
        label,
      },
      (iamRole: twirp.IIAMRole) => {
        onSuccess(iamRole);
        hideModal();
      },
      (e: string) => setErrorText(e),
    );
  };

  const submitDisabled = label === '' || isInvalidARN(arn);
  const arnInvalidError = arn !== '' && isInvalidARN(arn);

  return (
    <CustomModal title="Add IAM Role" isOpen={true} onClose={hideModal}>
      <Grid>
        <Column cols={12}>
          <Layout padding={1}>
            <FormGroup
              label="ARN"
              id="arn"
              orientation={FormGroupOrientation.Horizontal}
              error={arnInvalidError}
              errorMessage={arnInvalidError ? 'Invalid ARN' : undefined}
            >
              <Input
                type={InputType.Text}
                placeholder={PLACEHOLDER_IAM_ROLE}
                id="arn"
                onChange={handleArnChange}
                error={arnInvalidError}
              />
            </FormGroup>
          </Layout>
        </Column>
        <Column cols={12}>
          <Layout padding={1}>
            <FormGroup
              label="Label"
              id="label"
              orientation={FormGroupOrientation.Horizontal}
            >
              <Input
                type={InputType.Text}
                placeholder={PLACEHOLDER_IAM_ROLE_LABEL}
                id="label"
                onChange={handleLabelChange}
              />
            </FormGroup>
          </Layout>
        </Column>
        {errorText && (
          <Column cols={12}>
            <CoreText color={Color.Error}>{errorText}</CoreText>
          </Column>
        )}
        <Column cols={12}>
          <Layout
            padding={1}
            display={Display.Flex}
            justifyContent={JustifyContent.End}
          >
            <Button
              type={ButtonType.Success}
              onClick={handleIAMRoleSubmit}
              disabled={submitDisabled}
            >
              Register
            </Button>
          </Layout>
        </Column>
      </Grid>
    </CustomModal>
  );
};
