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

import twirp = code.justin.tv.eventbus.controlplane;
interface Props {
  publisherGrant: twirp.IAuthorizedFieldPublisherGrant;
  onSuccess: (pubGrant: twirp.IAuthorizedFieldPublisherGrant) => void;
}

export const ConfirmPublishDeleteModal = ({ publisherGrant, onSuccess }: Props) => {
  const [errorText, setErrorText] = useState('');
  const [deleteEnabled, setDeleteEnabled] = useState(false);
  setTimeout(() => {
    setDeleteEnabled(true);
  }, 3000);

  const { hideModal } = useContext(ModalContext);
  const deleteGrant = () => {
    deleteIAMRolePublication(
      publisherGrant,
      (deletedGrant: twirp.IAuthorizedFieldPublisherGrant) => {
        onSuccess(deletedGrant);
        hideModal();
      },
      (e: string) => {
        setErrorText(e);
      },
    );
  };

  return (
    <CustomModal title="Confirm Delete" isOpen={true} onClose={hideModal}>
      <Grid>
        <Column cols={12}>
          <CoreText><strong>Event Type:</strong> {publisherGrant.eventType}</CoreText>
          <CoreText><strong>IAM Role:</strong> {_.get(publisherGrant, 'iamRole.arn', '')}</CoreText>
          <CoreText><strong>Environment:</strong> {publisherGrant.environment}</CoreText>
        </Column>
        <Column cols={12}>
          <Layout padding={{ top: 1 }}>
            <CoreText><strong>Warning:</strong> deleting publication permisisons will cause your service to immediately stop publishing events to the event bus. Double check the information above before proceeding.</CoreText>
          </Layout>
        </Column>
        {errorText && (
          <Column cols={12}>
            <Layout padding={{ top: 1 }}>
              <CoreText color={Color.Error}>{errorText}</CoreText>
            </Layout>
          </Column>
        )}
        <Column cols={12}>
          <Layout
            padding={1}
            display={Display.Flex}
            justifyContent={JustifyContent.End}
          >
          {
            <Button
              type={ButtonType.Alert}
              onClick={deleteGrant}
              state={deleteEnabled ? ButtonState.Default : ButtonState.Loading}
              disabled={!deleteEnabled}
            >
              Delete
            </Button>
          }
          </Layout>
        </Column>
      </Grid>
    </CustomModal>
  );
};
