import { code } from 'dashboard/generated/controlplane';
import * as React from 'react';
import { useState } from 'react';
import Highlight from 'react-highlight.js';
import {
  AlignItems,
  Button,
  ButtonSize,
  ButtonType,
  Column,
  CoreText,
  Display,
  FlexDirection,
  FontSize,
  Grid,
  Layout,
  Overflow,
  StyledLayout,
  SVGAsset,
  Tabs,
  TabSize,
  Typeset,
} from 'twitch-core-ui';
import { AuthorizedFieldsTable } from './authorized-fields-table';
import { EventStreamUsage } from './event-stream-usage';

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

const baseViewURL =
  'https://git.xarth.tv/eventbus/schema/blob/master/events';

interface Props {
  event: twirp.IEventStream;
}

export const EventDetails = ({ event }: Props) => {
  const [activeTab, setActiveTab] = useState(0);

  const tabs = [
    <SchemaCode event={event} key="schema" />,
    <EventStreamUsage event={event} key="usage" />,
    <AuthorizedFieldsTable event={event} key="authorized-fields" />,
  ];

  return (
    <Layout padding={1}>
    <Grid>
      <Column cols={9}>
        <Layout display={Display.Flex}>
          <CoreText ellipsis fontSize={FontSize.Size3}>
            {event.displayName}
          </CoreText>
        </Layout>
      </Column>
      <Column cols={3}>
        <Layout
          display={Display.Flex}
          flexDirection={FlexDirection.Column}
          alignItems={AlignItems.End}
        >
          <Layout>
            <Layout>
              <Button
                type={ButtonType.Text}
                linkTo={`${baseViewURL}/${event.repoFilepath}`}
                icon={SVGAsset.Popout}
                size={ButtonSize.Small}
              >
                {`Edit schema`}
              </Button>
            </Layout>
          </Layout>
        </Layout>
      </Column>
      <Column cols={12}>
        <Layout margin={{ top: 2 }}>
          <Tabs
            activeTabIndex={activeTab}
            tabs={[
              { label: 'Schema', onClick: () => setActiveTab(0) },
              { label: 'Usage', onClick: () => setActiveTab(1) },
              { label: 'Authorized Fields', onClick: () => setActiveTab(2) },
            ]}
            size={TabSize.Large}
          />
        </Layout>
      </Column>
      <Column cols={12}>{tabs[activeTab]}</Column>
    </Grid>
    </Layout>
  );
};

interface SchemaCodeProps {
  event: twirp.IEventStream;
}
const SchemaCode = ({ event }: SchemaCodeProps) => (
  <StyledLayout overflow={Overflow.Hidden}>
    <StyledLayout elevation={2}>
      <Typeset>
        <CoreText className="code" fontSize={FontSize.Size6}>
          <Highlight language="protobuf">{event.schema}</Highlight>
        </CoreText>
      </Typeset>
    </StyledLayout>
  </StyledLayout>
);
