import { CustomModal } from 'dashboard/core/components/modal';
import { ModalContext } from 'dashboard/core/contexts/modals';
import { deleteIAMRole } from 'dashboard/core/utils/iam_role';
import * as React from 'react';
import { useContext, useState } from 'react';
import {
  Button,
  ButtonType,
  Color,
  CoreText,
  Display,
  FlexDirection,
  Layout,
  TextAlign,
} from 'twitch-core-ui';

interface DeleteIAMRoleModalProps {
  arn: string;
  isAllowed: boolean;
  onSuccess: (arn: string) => void;
}
export const DeleteIAMRoleModal = ({
  arn,
  isAllowed,
  onSuccess,
}: DeleteIAMRoleModalProps) => {
  const { hideModal } = useContext(ModalContext);
  const [error, setError] = useState<Error | null>(null);
  const onError = (e: Error) => setError(e);

  const handleDeleteIAMRole = () => {
    deleteIAMRole(
      arn,
      (deletedARN: string) => {
        onSuccess(deletedARN);
        hideModal();
      },
      onError,
    );
  };

  return (
    <CustomModal
      title={isAllowed ? 'Confirm Delete IAM Role' : 'Cannot Delete IAM Role'}
      isOpen={true}
      onClose={hideModal}
    >
      <Layout
        padding={1}
        className="modal-text-warning"
        textAlign={TextAlign.Center}
      >
        {isAllowed && (
          <>
            <Layout padding={0.5}>
              <CoreText>
                Are you sure you want to deregister this IAM role?
              </CoreText>
            </Layout>
            <Layout
              padding={0.5}
              display={Display.Flex}
              flexDirection={FlexDirection.Row}
            >
              <Layout margin={{ x: 0.5 }}>
                <CoreText bold>ARN:</CoreText>
              </Layout>
              <Layout margin={{ x: 0.5 }}>
                <CoreText>{arn}</CoreText>
              </Layout>
            </Layout>
            {error && (
              <Layout padding={{ y: 2, x: 0.5 }}>
                <CoreText color={Color.Error}>{error.message}</CoreText>
              </Layout>
            )}
            <Layout padding={{ y: 1, x: 0.5 }}>
              <Button onClick={handleDeleteIAMRole} type={ButtonType.Alert}>Delete</Button>
            </Layout>
          </>
        )}
        {!isAllowed && (
          <CoreText color={Color.Alt2}>
            You may not remove an IAM role from the dashboard unless all granted
            publisher and subscriber permissions are removed.
          </CoreText>
        )}
      </Layout>
    </CustomModal>
  );
};
