import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useQuery } from '@apollo/client';
import { ALLIANCE } from 'components/alliance/schema/queries';
import { AllianceQuery, AllianceQueryVariables } from 'types/graphql';

import { Box, Heading } from 'components/common';
import {
  SidebarExactNavLink,
  SidebarCloseButton,
} from 'components/sidebar/Sidebar';
import { SidebarLinks } from './SidebarLinks';

import { assignParams } from 'components/router/assignParams';

import { PATHS as ALLIANCE_PAGE } from '../index';
import { ANALYTICS_NAVIGATION_KEY } from '../AllianceSidebar';

export const AllianceAnalyticsNavigation = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { [ALLIANCE_PAGE.allianceId]: allianceId } = useParams();

  const { data } = useQuery<AllianceQuery, AllianceQueryVariables>(ALLIANCE, {
    variables: { allianceId: allianceId! },
    fetchPolicy: 'cache-only',
  });

  const closeSidebar = () => {
    navigate(
      {
        ...location,
        search: assignParams(location.search, (s) => {
          s.delete(ANALYTICS_NAVIGATION_KEY);
        }),
      },
      { replace: true }
    );
  };

  return (
    <div className="flex flexColumn" style={{ paddingBottom: 100 }}>
      <Box
        flex="none"
        height={48}
        display="flex"
        align="center"
        justify="between"
        className="bg-white"
      >
        <Box className="bold fz16" paddingX={3}>
          Analytics
        </Box>
        <SidebarCloseButton onClick={closeSidebar} />
      </Box>

      <SidebarExactNavLink
        to={{
          pathname: location.pathname,
          search: assignParams(location.search, (s) => {
            s.delete(ALLIANCE_PAGE.collection);
          }),
          hash: location.hash,
        }}
      >
        All fans
      </SidebarExactNavLink>
      <div className="hr"></div>
      <Heading className="mb2 paddingX3" size="s">
        Collections
      </Heading>
      <SidebarLinks
        items={data!.alliance.collections}
        pathname={ALLIANCE_PAGE.analytics}
        queryKey={ALLIANCE_PAGE.collection}
      />
      <div className="hr"></div>
      <Heading className="mb2 paddingX3" size="s">
        Segments
      </Heading>
      <SidebarLinks
        items={data!.alliance.segments}
        pathname={ALLIANCE_PAGE.analytics}
        queryKey={ALLIANCE_PAGE.collection}
      />
    </div>
  );
};
