import { Errored } from 'dashboard/core/components/errored';
import { useEventStream } from 'dashboard/core/utils/event-stream';
import { AuthFieldsSubscriptionTab } from 'dashboard/pages/event-manage/components/auth-fields-subscriptions-tab';
import { PublishPermissionsTab } from 'dashboard/pages/event-manage/components/publish-permissions-tab';
import * as React from 'react';
import { useEffect, useState } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import {
  Column,
  CoreText,
  Grid,
  Layout,
  LoadingSpinner,
  TabItemPublicProps,
  Tabs,
  TabSize,
  TextType,
} from 'twitch-core-ui';

const AUTHORIZED_FIELD_SUBSCRIBER_GRANTS_TAB = 0;
const PUBLISHER_TAB = 1;

export interface PrefilledGrantData {
  messageName: string;
  fieldName: string;
  iamRoleARN: string;
  environment: string;
}

const usePrefilledGrantData = (): PrefilledGrantData | undefined => {
  const params = new URLSearchParams(useLocation().search);

  const messageName = params.get('msg');
  const fieldName = params.get('field');
  const iamRoleARN = params.get('arn');
  const environment = params.get('env');

  if (messageName && fieldName && iamRoleARN && environment) {
    return {
      messageName,
      fieldName,
      iamRoleARN,
      environment,
    };
  } else {
    return undefined;
  }
};

interface EventManagementParams {
  eventType: string;
}

export const EventManagePage = () => {
  const { eventType } = useParams<EventManagementParams>();

  // Use the production event stream to get a list of available authorized fields for the event type
  const { eventStream, loading, error } = useEventStream(
    eventType,
    'production',
  );

  const [activeTab, setActiveTab] = useState(0);
  const onClick = (_onClick: React.MouseEvent<HTMLElement>, index: number) => {
    setActiveTab(index);
  };
  const exampleTabs: TabItemPublicProps[] = [
    { label: 'Authorized Field Subscriber Permissions', onClick },
    { label: 'Publisher Permissions', onClick },
  ];

  // If magic link is present switch to the subscriber grant tab
  const prefilledGrantData = usePrefilledGrantData();
  useEffect(() => {
    if (prefilledGrantData) {
      setActiveTab(AUTHORIZED_FIELD_SUBSCRIBER_GRANTS_TAB);
    }
  }, [prefilledGrantData]);

  return (
    <Grid>
      {loading && <LoadingSpinner />}
      {error && <Errored text={error.message} />}
      {!loading && (
        <>
          <Column cols={12}>
            <Layout padding={1}>
              <CoreText type={TextType.H3}>{eventType}</CoreText>
            </Layout>
          </Column>
          <Column cols={12}>
            <Layout padding={1}>
              <Tabs
                activeTabIndex={activeTab}
                tabs={exampleTabs}
                size={TabSize.Large}
              />
            </Layout>
          </Column>
          {activeTab === AUTHORIZED_FIELD_SUBSCRIBER_GRANTS_TAB && (
            <Column cols={12}>
              <AuthFieldsSubscriptionTab
                eventType={eventType}
                authorizedFields={eventStream!.authorizedFields!}
                prefilledGrantData={prefilledGrantData}
              />
            </Column>
          )}
          {activeTab === PUBLISHER_TAB && (
            <Column cols={12}>
              <PublishPermissionsTab eventType={eventType} />
            </Column>
          )}
        </>
      )}
    </Grid>
  );
};
