import { BannerContext } from 'dashboard/core/contexts/banners';
import { ModalContext } from 'dashboard/core/contexts/modals';
import { useLDAPGroups } from 'dashboard/core/utils/ldap';
import { serviceCatalogIDs, useServices } from 'dashboard/core/utils/service';
import { code } from 'dashboard/generated/controlplane';
import { CreateServiceModal } from 'dashboard/pages/services/components/create-service-modal';
import { ServicesTable } from 'dashboard/pages/services/components/services-table';
import * as _ from 'lodash';
import * as React from 'react';
import { useContext, useEffect, useState } from 'react';
import { RouteComponentProps } from 'react-router';
import {
  AlertBannerType,
  AlignItems,
  Button,
  Color,
  Column,
  CoreText,
  Display,
  FlexDirection,
  Grid,
  JustifyContent,
  Layout,
  LoadingSpinner,
  StyledLayout,
  SVG,
  SVGAsset,
  TextType,
} from 'twitch-core-ui';

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

export type RouteProps = RouteComponentProps<{}>;

type Props = RouteProps;

export const ServicesPage = ({}: Props) => {
  const { showBanner } = useContext(BannerContext);

  const { services, loading, error } = useServices();
  const { ldapGroups } = useLDAPGroups();

  const [displayedServices, setDisplayedServices] = useState(
    new Array<twirp.IService>(),
  );
  useEffect(() => {
    setDisplayedServices(services);
  }, [services]);

  const { showModal } = useContext(ModalContext);

  const handleCreateServiceSuccess = (service: twirp.IService) => {
    setDisplayedServices(_.sortBy([...displayedServices, service], ['name']));
    showBanner({
      type: AlertBannerType.Success,
      status: 'Success!',
      message: 'Your service has been added',
      id: 'service-created',
      link: {
        text: 'Go there now',
        href: `/services/${service.id}`,
      },
    });
  };

  const handleShowCreateServiceModal = () => {
    showModal({
      component: CreateServiceModal,
      props: {
        ldapGroups,
        existingServiceCatalogIDs: serviceCatalogIDs(services),
        onCreateSuccess: handleCreateServiceSuccess,
      },
    });
  };

  if (loading) {
    return (
      <StyledLayout
        padding={1}
        display={Display.Flex}
        alignItems={AlignItems.Center}
        justifyContent={JustifyContent.Center}
      >
        <LoadingSpinner />
      </StyledLayout>
    );
  } else if (error) {
    return (
      <StyledLayout
        padding={1}
        display={Display.Flex}
        justifyContent={JustifyContent.Center}
      >
        <Layout padding={1} alignItems={AlignItems.Center}>
          <SVG asset={SVGAsset.DeadGlitch} />
        </Layout>
        <Layout padding={1} alignItems={AlignItems.Center}>
          <CoreText type={TextType.P} color={Color.Alt2}>
            Error fetching services...
          </CoreText>
        </Layout>
      </StyledLayout>
    );
  }

  return (
    <Grid>
      <Column cols={9}>
        <StyledLayout padding={0.5}>
          <CoreText type={TextType.H3}>Services</CoreText>
        </StyledLayout>
      </Column>
      <Column cols={3}>
        <StyledLayout
          display={Display.Flex}
          flexDirection={FlexDirection.RowReverse}
          padding={0.5}
        >
          <Button
            onClick={handleShowCreateServiceModal}
            icon={SVGAsset.AddReaction}
          >
            Add Your Service
          </Button>
        </StyledLayout>
      </Column>
      <Column cols={12}>
        <StyledLayout padding={0.5}>
          <ServicesTable services={displayedServices as twirp.Service[]} />
        </StyledLayout>
      </Column>
    </Grid>
  );
};
