import twirp = code.justin.tv.eventbus.controlplane;
import { CustomModal } from 'dashboard/core/components/modal';
import { ModalContext } from 'dashboard/core/contexts/modals';
import { createSubscription } from 'dashboard/core/utils/subscriptions';
import { code } from 'dashboard/generated/controlplane';
import * as React from 'react';
import { useContext, useState } from 'react';
import {
  Button,
  ButtonState,
  ButtonType,
  Color,
  CoreText,
  Display,
  FlexDirection,
  FontSize,
  JustifyContent,
  Layout,
  TextAlign,
} from 'twitch-core-ui';

interface Props {
  targetId: string;
  eventType: string;
  environment: string;
  onCreateSuccess: (_: twirp.ISubscription) => void;
  onError: (_: Error) => void;
}
export const AddSubscriptionModal = ({
  targetId,
  eventType,
  environment,
  onCreateSuccess,
  onError,
}: Props) => {
  const { hideModal } = useContext(ModalContext);

  const [loading, setLoading] = useState(false);

  const subscription = {
    targetId,
    eventType,
    environment,
  };

  const handleCreateSubscription = () => {
    setLoading(true);
    createSubscription(
      subscription,
      (s: twirp.ISubscription) => {
        onCreateSuccess(s);
        setLoading(false);
        hideModal();
      },
      onError,
    );
  };

  return (
    <CustomModal title="Confirm Subscription" isOpen={true} onClose={hideModal}>
      <Layout
        display={Display.Flex}
        flexDirection={FlexDirection.Row}
        justifyContent={JustifyContent.Center}
      >
        <Layout
          display={Display.Flex}
          padding={1}
          flexDirection={FlexDirection.Column}
        >
          <Layout>
            <CoreText bold>Event:</CoreText>
          </Layout>
          <Layout>
            <CoreText bold>Environment:</CoreText>
          </Layout>
        </Layout>

        <Layout
          display={Display.Flex}
          padding={1}
          flexDirection={FlexDirection.Column}
        >
          <Layout>
            <CoreText>{eventType}</CoreText>
          </Layout>
          <Layout>
            <CoreText>{environment}</CoreText>
          </Layout>
        </Layout>
      </Layout>

      <Layout
        padding={1}
        className="modal-text-warning"
        textAlign={TextAlign.Center}
      >
        <CoreText color={Color.Alt2} fontSize={FontSize.Size7}>
          Are you sure you want to subscribe to this event stream? This
          subscription target will begin receiving these events immediately.
          Please ensure you have the proper handler implemented.
        </CoreText>
      </Layout>
      <Layout
        padding={1}
        display={Display.Flex}
        justifyContent={JustifyContent.Center}
      >
        <Button onClick={handleCreateSubscription} type={ButtonType.Success} state={loading ? ButtonState.Loading : ButtonState.Default}>
          Subscribe
        </Button>
      </Layout>
    </CustomModal>
  );
};
