import { CustomModal } from 'dashboard/core/components/modal';
import { ModalContext } from 'dashboard/core/contexts/modals';
import { deregisterTarget } from 'dashboard/core/utils/target';
import { code } from 'dashboard/generated/controlplane';
import * as React from 'react';
import { useContext, useState } from 'react';
import {
  Button,
  ButtonSize,
  ButtonType,
  Color,
  CoreText,
  Display,
  FontSize,
  JustifyContent,
  Layout,
  TextAlign,
} from 'twitch-core-ui';

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

interface Props {
  target: twirp.ITarget;
  onSuccess: (_: twirp.ITarget) => void;
}
export const DeregisterTargetModal = ({ target, onSuccess }: Props) => {
  const { hideModal } = useContext(ModalContext);
  const [error, setError] = useState<Error | null>(null);
  const onError = (e: Error) => setError(e);

  const handleDeregisterTarget = () => {
    deregisterTarget(
      target,
      (t: twirp.ITarget) => {
        onSuccess(t);
        hideModal();
      },
      onError,
    );
  };

  return (
    <CustomModal title="Confirm Deregister" isOpen={true} onClose={hideModal}>
      <Layout
        padding={1}
        className="modal-text-warning"
        textAlign={TextAlign.Center}
      >
        <Layout margin={1}>
          <CoreText fontSize={FontSize.Size5} color={Color.Error}>
            You are attempting to deregister the following SQS Queue:
          </CoreText>
        </Layout>
        <Layout
          margin={1}
          display={Display.Flex}
          justifyContent={JustifyContent.Center}
        >
          <CoreText fontSize={FontSize.Size5} color={Color.Error} bold>
            {target.name}
          </CoreText>
        </Layout>
        <Layout
          margin={1}
          display={Display.Flex}
          justifyContent={JustifyContent.Center}
        >
          <CoreText fontSize={FontSize.Size5} color={Color.Error} bold>
            {target.sqs?.queueUrl}
          </CoreText>
        </Layout>
        <Layout margin={1}>
          <CoreText fontSize={FontSize.Size5}>
            Deregistering will allow you to safely remove the queue from your
            AWS Account. Please ensure that this queue has no active
            subscriptions before deregistering!
          </CoreText>
        </Layout>
        {error && (
          <Layout padding={{ bottom: 1 }}>
            <CoreText color={Color.Error}>{error.message}</CoreText>
          </Layout>
        )}
      </Layout>
      <Layout display={Display.Flex} justifyContent={JustifyContent.Center}>
        <Button
          size={ButtonSize.Large}
          onClick={handleDeregisterTarget}
          type={ButtonType.Alert}
        >
          Deregister
        </Button>
      </Layout>
    </CustomModal>
  );
};
